<commit_before>import datetime
import urllib
from dateutil.rrule import *
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.contrib.localflavor.us.us_states import STATE_CHOICES
from django.core.urlresolvers import reverse

SCHEDULE_PATTERN_TYPE_CHOICES = (
    ('One-Off', 'One-Off'),
    ('Days of Week', 'Days of Week'),
    ('Days of Alt Week', 'Days of Alternating Week'),
    ('Day of Month', 'Day of Month'),
)

dateformat = '{d:%b %d, %Y}'
datetimeformat = '{d:%b %d, %Y} ({d.hour}:{d.minute:02} {d:%p})'

#days_of_week_dict maps our day strings "M", "Tu", ... to the dateutil objects MO, TU, ...
days_of_week_dict = {'M': MO, 'Tu': TU, 'W': WE, 'Th': TH, 'F': FR, 'Sa': SA, 'Su': SU}
days_of_week_list = ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su']
days_of_week_choices = (('M', 'Mo'), ('Tu', 'Tu'), ('W', 'We'), ('Th', 'Th'), ('F', 'Fr'), ('Sa', 'Sa'), ('Su', 'Su'))


class Volunteer(models.Model):
    user = models.OneToOneField(User, db_column='userId')
    trained = models.BooleanField(default=False)
    clients = models.ManyToManyField('Client', related_name='volunteers')
    phone = models.CharField(max_length=20, null=True, blank=True)

    def __unicode__(self):
        return self.user.first_name + " " + self.user.last_name if (
        self.user.first_name or self.user.last_name) else self.user.email

    def get_absolute_url(self):
        return reverse('timeslots_volunteer_view', kwargs={'userid': self.user.id})

    def get_absolute_edit_url(self):
        return reverse('timeslots_volunteer_edit', kwargs={'userid': self.user.id})

    def get_absolute_list_url(self):
        """ URL for list of Volunteers """
        return reverse('timeslots_volunteers_view')

    def get_clean_model_name(self):
        return "Volunteer"

    def get_current_commitments(self):
        from django.db.models import Q

        today = timezone.now()
        return self.commitments.filter(Q(endDate__gte=today) | Q(endDate__isnull=True), startDate__lte=today)

    def get_commitments(self, client=None):
        from django.db.models import Q

        today = timezone.now()
        if client:
            commitments = self.commitments.filter(Q(endDate__gte=today) | Q(endDate__isnull=True), startDate__lte=today, clientOpening__client=client)
        else:
            commitments = self.commitments.filter(Q(endDate__gte=today) | Q(endDate__isnull=True), startDate__lte=today)
        return commitments

    def get_commitment_instances(self, startDate=None, endDate=None, client=None, **kwargs):
        instances = list()
        for commitment in self.get_commitments(client=client):
            instances.extend(commitment.get_instances(startDate=startDate, endDate=endDate, **kwargs))
        instances.sort(key=lambda item:item['date'])
        return instances

    def get_unfilled_client_opening_instances(self, startDate=None, endDate=None, **kwargs):
        openings = list()
        for opening in ClientOpening.objects.filter(client__volunteers=self):
            openings.extend(opening.get_unfilled_instances(startDate=startDate, endDate=endDate))
        openings.sort(key=lambda item:item['date'])
        return openings


class Client(models.Model):
    user = models.OneToOneField(User, db_column='userId')
    address = models.CharField(max_length=255, blank=True, null=True)
    address2 = models.CharField(max_length=255, blank=True, null=True)
    city = models.CharField(max_length=255, blank=True, null=True)
    state = models.CharField(max_length=2, choices=STATE_CHOICES, blank=True, null=True)
    zipcode = models.CharField(max_length=10, blank=True, null=True)
    phone = models.CharField(max_length=20, null=True, blank=True)

    def __unicode__(self):
        return self.user.first_name + " " + self.user.last_name if (
        self.user.first_name or self.user.last_name) else self.user.email

    def get_absolute_url(self):
        return reverse('timeslots_client_view', kwargs={'userid': self.user.id})

    def get_absolute_edit_url(self):
        return reverse('timeslots_client_edit', kwargs={'userid': self.user.id})

    def get_absolute_list_url(self):
        """ URL for list of Clients """
        return reverse('timeslots_clients_view')

    def get_clean_model_name(self):
        return "Client"

    def get_opening_instances(self, **kwargs):
        instances = list()
        for opening in self.openings.all():
            instances.extend(opening.get_next_instances(**kwargs))
        instances.sort()
        return instances

    def get_unfilled_opening_instances(self, **kwargs):
        instances = list()
        for opening in self.openings.all():
            instances.extend(opening.get_unfilled_instances(**kwargs))
        instances.sort()
        return instances

    def get_commitments(self, **kwargs):
        openings = self.openings.all()
        commitments = list()
        for opening in openings:
            commitments.extend(opening.volunteercommitment_set.all())
        return commitments

    def get_unfilled_openings(self, **kwargs):
        # this includes all openings for the client which are not ENTIRELY filled
        openings = (x for x in self.openings.all() if not x.is_filled())
        return openings

    def get_address_urlencoded(self, **kwargs):
        # for Google Maps link
        addressString = self.address + ", " + self.city + " " + self.state + " " + self.zipcode
        urlEncoded = urllib.urlencode({ 'q': addressString })
        return urlEncoded


class ClientOpening(models.Model):
    client = models.ForeignKey(Client, db_column='clientId', related_name='openings')
    startDate = models.DateTimeField('Start Date', default=timezone.now())
    endDate = models.DateTimeField('End Date', blank=True, null=True)
    type = models.CharField(max_length=20, choices=SCHEDULE_PATTERN_TYPE_CHOICES, default='Days of Week')
    notes = models.CharField(max_length=255, blank=True, null=True)

    def __unicode__(self):
        return "%s, %s: %s (%s-%s)" % (self.client, self.type, self.get_all_metadata_string(), dateformat.format(d=self.startDate), dateformat.format(d=self.endDate) if self.endDate is not None else "")

    def get_absolute_url(self):
        return reverse('timeslots_opening_view', kwargs={'openingid': self.id})

    def get_absolute_edit_url(self):
        return reverse('timeslots_opening_edit', kwargs={'openingid': self.id})

    def get_absolute_list_url(self):
        """ URL for list of Openings """
        return reverse('timeslots_openings_view')

    def get_absolute_list_for_client_url(self):
        """ URL for list of Openings for this client """<commit_msg>Fix bug when new ClientOpening is created where it defaults to weird time<commit_after>import datetime
import urllib
from dateutil.rrule import *
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.contrib.localflavor.us.us_states import STATE_CHOICES
from django.core.urlresolvers import reverse

SCHEDULE_PATTERN_TYPE_CHOICES = (
    ('One-Off', 'One-Off'),
    ('Days of Week', 'Days of Week'),
    ('Days of Alt Week', 'Days of Alternating Week'),
    ('Day of Month', 'Day of Month'),
)

dateformat = '{d:%b %d, %Y}'
datetimeformat = '{d:%b %d, %Y} ({d.hour}:{d.minute:02} {d:%p})'

#days_of_week_dict maps our day strings "M", "Tu", ... to the dateutil objects MO, TU, ...
days_of_week_dict = {'M': MO, 'Tu': TU, 'W': WE, 'Th': TH, 'F': FR, 'Sa': SA, 'Su': SU}
days_of_week_list = ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su']
days_of_week_choices = (('M', 'Mo'), ('Tu', 'Tu'), ('W', 'We'), ('Th', 'Th'), ('F', 'Fr'), ('Sa', 'Sa'), ('Su', 'Su'))


class Volunteer(models.Model):
    user = models.OneToOneField(User, db_column='userId')
    trained = models.BooleanField(default=False)
    clients = models.ManyToManyField('Client', related_name='volunteers')
    phone = models.CharField(max_length=20, null=True, blank=True)

    def __unicode__(self):
        return self.user.first_name + " " + self.user.last_name if (
        self.user.first_name or self.user.last_name) else self.user.email

    def get_absolute_url(self):
        return reverse('timeslots_volunteer_view', kwargs={'userid': self.user.id})

    def get_absolute_edit_url(self):
        return reverse('timeslots_volunteer_edit', kwargs={'userid': self.user.id})

    def get_absolute_list_url(self):
        """ URL for list of Volunteers """
        return reverse('timeslots_volunteers_view')

    def get_clean_model_name(self):
        return "Volunteer"

    def get_current_commitments(self):
        from django.db.models import Q

        today = timezone.now()
        return self.commitments.filter(Q(endDate__gte=today) | Q(endDate__isnull=True), startDate__lte=today)

    def get_commitments(self, client=None):
        from django.db.models import Q

        today = timezone.now()
        if client:
            commitments = self.commitments.filter(Q(endDate__gte=today) | Q(endDate__isnull=True), startDate__lte=today, clientOpening__client=client)
        else:
            commitments = self.commitments.filter(Q(endDate__gte=today) | Q(endDate__isnull=True), startDate__lte=today)
        return commitments

    def get_commitment_instances(self, startDate=None, endDate=None, client=None, **kwargs):
        instances = list()
        for commitment in self.get_commitments(client=client):
            instances.extend(commitment.get_instances(startDate=startDate, endDate=endDate, **kwargs))
        instances.sort(key=lambda item:item['date'])
        return instances

    def get_unfilled_client_opening_instances(self, startDate=None, endDate=None, **kwargs):
        openings = list()
        for opening in ClientOpening.objects.filter(client__volunteers=self):
            openings.extend(opening.get_unfilled_instances(startDate=startDate, endDate=endDate))
        openings.sort(key=lambda item:item['date'])
        return openings


class Client(models.Model):
    user = models.OneToOneField(User, db_column='userId')
    address = models.CharField(max_length=255, blank=True, null=True)
    address2 = models.CharField(max_length=255, blank=True, null=True)
    city = models.CharField(max_length=255, blank=True, null=True)
    state = models.CharField(max_length=2, choices=STATE_CHOICES, blank=True, null=True)
    zipcode = models.CharField(max_length=10, blank=True, null=True)
    phone = models.CharField(max_length=20, null=True, blank=True)

    def __unicode__(self):
        return self.user.first_name + " " + self.user.last_name if (
        self.user.first_name or self.user.last_name) else self.user.email

    def get_absolute_url(self):
        return reverse('timeslots_client_view', kwargs={'userid': self.user.id})

    def get_absolute_edit_url(self):
        return reverse('timeslots_client_edit', kwargs={'userid': self.user.id})

    def get_absolute_list_url(self):
        """ URL for list of Clients """
        return reverse('timeslots_clients_view')

    def get_clean_model_name(self):
        return "Client"

    def get_opening_instances(self, **kwargs):
        instances = list()
        for opening in self.openings.all():
            instances.extend(opening.get_next_instances(**kwargs))
        instances.sort()
        return instances

    def get_unfilled_opening_instances(self, **kwargs):
        instances = list()
        for opening in self.openings.all():
            instances.extend(opening.get_unfilled_instances(**kwargs))
        instances.sort()
        return instances

    def get_commitments(self, **kwargs):
        openings = self.openings.all()
        commitments = list()
        for opening in openings:
            commitments.extend(opening.volunteercommitment_set.all())
        return commitments

    def get_unfilled_openings(self, **kwargs):
        # this includes all openings for the client which are not ENTIRELY filled
        openings = (x for x in self.openings.all() if not x.is_filled())
        return openings

    def get_address_urlencoded(self, **kwargs):
        # for Google Maps link
        addressString = self.address + ", " + self.city + " " + self.state + " " + self.zipcode
        urlEncoded = urllib.urlencode({ 'q': addressString })
        return urlEncoded


class ClientOpening(models.Model):
    client = models.ForeignKey(Client, db_column='clientId', related_name='openings')
    startDate = models.DateTimeField('Start Date', default=timezone.now().replace(hour=12, minute=0, second=0, microsecond=0))
    endDate = models.DateTimeField('End Date', blank=True, null=True)
    type = models.CharField(max_length=20, choices=SCHEDULE_PATTERN_TYPE_CHOICES, default='Days of Week')
    notes = models.CharField(max_length=255, blank=True, null=True)

    def __unicode__(self):
        return "%s, %s: %s (%s-%s)" % (self.client, self.type, self.get_all_metadata_string(), dateformat.format(d=self.startDate), dateformat.format(d=self.endDate) if self.endDate is not None else "")

    def get_absolute_url(self):
        return reverse('timeslots_opening_view', kwargs={'openingid': self.id})

    def get_absolute_edit_url(self):
        return reverse('timeslots_opening_edit', kwargs={'openingid': self.id})

    def get_absolute_list_url(self):
        """ URL for list of Openings """
        return reverse('timeslots_openings_view')

    def get_absolute_list_for_client_url(self):
        """ URL for list of Openings for this client """
{'fraction_non_alphanumeric': 0.1292466765140325, 'fraction_numerical': 0.003914327917282127, 'mean_word_length': 3.830895469140207, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '310324', 'n_tokens_mistral': 4365, 'n_tokens_neox': 4241, 'n_words': 927}