Repository: dotkom/onlineweb4

Issue:
Marks have no way of knowing their expiry date
Due to the way active marks are calculated today, there is no way for a mark to find out when it's expiry date is.

A solution for this would be to fecator get_threshold() to use another method which calculates the offset, and then use this offset to give the expiry date.



Discussion:

Resolving patch:
diff --git a/apps/marks/migrations/0003_auto__del_field_mark_mark_added_date__add_field_mark_added_date__add_f.py b/apps/marks/migrations/0003_auto__del_field_mark_mark_added_date__add_field_mark_added_date__add_f.py
new file mode 100644
--- /dev/null
+++ b/apps/marks/migrations/0003_auto__del_field_mark_mark_added_date__add_field_mark_added_date__add_f.py
@@ -0,0 +1,110 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Deleting field 'Mark.mark_added_date'
+        db.delete_column(u'marks_mark', 'mark_added_date')
+
+        # Adding field 'Mark.added_date'
+        db.add_column(u'marks_mark', 'added_date',
+                      self.gf('django.db.models.fields.DateField')(default=datetime.datetime(2013, 11, 18, 0, 0)),
+                      keep_default=False)
+
+        # Adding field 'Mark.expiration_date'
+        db.add_column(u'marks_mark', 'expiration_date',
+                      self.gf('django.db.models.fields.DateField')(default=datetime.datetime(2013, 11, 18, 0, 0)),
+                      keep_default=False)
+
+
+    def backwards(self, orm):
+        # Adding field 'Mark.mark_added_date'
+        db.add_column(u'marks_mark', 'mark_added_date',
+                      self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, default=datetime.datetime(2013, 11, 18, 0, 0), blank=True),
+                      keep_default=False)
+
+        # Deleting field 'Mark.added_date'
+        db.delete_column(u'marks_mark', 'added_date')
+
+        # Deleting field 'Mark.expiration_date'
+        db.delete_column(u'marks_mark', 'expiration_date')
+
+
+    models = {
+        u'auth.group': {
+            'Meta': {'object_name': 'Group'},
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+        },
+        u'auth.permission': {
+            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
+            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        u'authentication.onlineuser': {
+            'Meta': {'ordering': "['first_name', 'last_name']", 'object_name': 'OnlineUser'},
+            'address': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
+            'allergies': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
+            'compiled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+            'field_of_study': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
+            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'image': ('django.db.models.fields.files.ImageField', [], {'default': "'/static/img/profile_default.png'", 'max_length': '200', 'null': 'True', 'blank': 'True'}),
+            'infomail': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+            'mark_rules': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+            'nickname': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
+            'ntnu_username': ('django.db.models.fields.CharField', [], {'max_length': '10', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
+            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+            'phone_number': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
+            'rfid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
+            'started_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2013, 11, 18, 0, 0)'}),
+            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
+            'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
+            'zip_code': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'})
+        },
+        u'contenttypes.contenttype': {
+            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+        },
+        u'marks.mark': {
+            'Meta': {'object_name': 'Mark'},
+            'added_date': ('django.db.models.fields.DateField', [], {}),
+            'category': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
+            'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
+            'expiration_date': ('django.db.models.fields.DateField', [], {}),
+            'given_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'mark_given_by'", 'null': 'True', 'to': u"orm['authentication.OnlineUser']"}),
+            'given_to': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['authentication.OnlineUser']", 'null': 'True', 'through': u"orm['marks.UserEntry']", 'blank': 'True'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'last_changed_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'marks_last_changed_by'", 'null': 'True', 'to': u"orm['authentication.OnlineUser']"}),
+            'last_changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
+            'title': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+        },
+        u'marks.userentry': {
+            'Meta': {'unique_together': "(('user', 'mark'),)", 'object_name': 'UserEntry'},
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'mark': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['marks.Mark']"}),
+            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authentication.OnlineUser']"})
+        }
+    }
+
+    complete_apps = ['marks']
\ No newline at end of file
diff --git a/apps/marks/models.py b/apps/marks/models.py
--- a/apps/marks/models.py
+++ b/apps/marks/models.py
@@ -1,26 +1,22 @@
 #-*- coding: utf-8 -*-
 
-import datetime
-from django.utils import timezone
+from datetime import date, datetime, time, timedelta
 
 from django.conf import settings
 from django.db import models
+from django.utils import timezone
 from django.utils.translation import ugettext as _
 
 from apps.authentication.models import OnlineUser as User
 
 class ActiveMarksManager(models.Manager):
     def get_query_set(self):
-        threshhold = get_threshold()
-
-        return super(ActiveMarksManager, self).get_query_set().filter(mark_added_date__gt=threshhold)
+        return super(ActiveMarksManager, self).get_query_set().filter(expiration_date__gt=timezone.now())
 
 
 class InactiveMarksManager(models.Manager):
     def get_query_set(self):
-        threshhold = get_threshold()
-
-        return super(InactiveMarksManager, self).get_query_set().filter(mark_added_date__lte=threshhold)
+        return super(InactiveMarksManager, self).get_query_set().filter(expiration_date__lte=timezone.now())
 
 
 class Mark(models.Model):
@@ -35,7 +31,8 @@ class Mark(models.Model):
 
     title = models.CharField(_(u"tittel"), max_length=50)
     given_to = models.ManyToManyField(User, null=True, blank=True, through="UserEntry", verbose_name=_(u"gitt til"))
-    mark_added_date = models.DateTimeField(_(u"utdelt dato"), auto_now_add=True)
+    added_date = models.DateField(_(u"utdelt dato"))
+    expiration_date = models.DateField(_(u"utløpsdato"), editable=False)
     given_by = models.ForeignKey(User, related_name="mark_given_by", verbose_name=_(u"gitt av"), editable=False, null=True, blank=True)
     last_changed_date = models.DateTimeField(_(u"sist redigert"), auto_now=True, editable=False)
     last_changed_by = models.ForeignKey(User, related_name="marks_last_changed_by",
@@ -53,11 +50,17 @@ class Mark(models.Model):
 
     @property
     def is_active(self):
-        return timezone.make_naive(self.mark_added_date, timezone.get_current_timezone()) > get_threshold()
+        return self.expiration_date > timezone.now()
 
     def __unicode__(self):
         return _(u"Prikk for %s") % self.title
 
+    def save(self, *args, **kwargs):
+        if not self.added_date:
+            self.added_date = timezone.now()
+        self.expiration_date = _get_expiration_date(self.added_date) 
+        super(Mark, self).save(*args, **kwargs)
+
     class Meta:
         verbose_name = _(u"Prikk")
         verbose_name_plural = _(u"Prikker")
@@ -74,39 +77,45 @@ class Meta:
         unique_together = ("user", "mark")
 
 
-def get_threshold():
+def _get_expiration_date(added_date=timezone.now()):
+    """
+    Calculates the datetime in the future when a mark will expire. 
+    """
+
+    if type(added_date) == datetime:
+        added_date = added_date.date()
+
     DURATION = 60
     # summer starts 1st June, ends 15th August
     SUMMER = ((6, 1), (8, 15))
     # winter starts 1st December, ends 15th January
     WINTER = ((12, 1), (1, 15))
 
-    # Todays date
-    now = datetime.datetime.now().date()
-    # Threshhold is the day in the past which marks will be filtered on by mark_added_date
-    threshold = now - datetime.timedelta(days=DURATION)
-    summer_start_date = datetime.date(now.year, SUMMER[0][0], SUMMER[0][1])
-    summer_end_date = datetime.date(now.year, SUMMER[1][0], SUMMER[1][1])
-    first_winter_start_date = datetime.date(now.year - 1, WINTER[0][0], WINTER[0][1])
-    first_winter_end_date = datetime.date(now.year, WINTER[1][0], WINTER[1][1])
-    second_winter_start_date = datetime.date(now.year, WINTER[0][0], WINTER[0][1])
-
-    # If we're in the middle of summer, remove the days passed of summer
-    if summer_start_date < now < summer_end_date:
-        threshold -= datetime.timedelta(days=(now - summer_start_date).days)
-    # If the number of days between now and the end of the summer vacation is less than
-    # the duration, we need to remove the length of summer from the threshhold
-    elif 0 < (now - summer_end_date).days < DURATION:
-        threshold -= datetime.timedelta(days=(summer_end_date - summer_start_date).days)
-    # Same for middle of winter vacation, which will be after newyears
-    elif first_winter_start_date < now < first_winter_end_date:
-        threshold -= datetime.timedelta(days=(now - first_winter_start_date).days)
-    # And for after the vacation
-    elif 0 < (now - first_winter_end_date).days < DURATION:
-        threshold -= datetime.timedelta(days=(first_winter_end_date - first_winter_start_date).days)
-    # Then we need to check if we're into the start of the vacation this year, i.e. before newyears
-    elif second_winter_start_date < now:
-        threshold -= datetime.timedelta(days=(now - second_winter_start_date).days)
-
-    # The returned value is a datetime object
-    return datetime.datetime.combine(threshold, datetime.time())
+    # Add the duration
+    expiry_date = added_date + timedelta(days=DURATION)
+    # Set up the summer and winter vacations
+    summer_start_date = date(added_date.year, SUMMER[0][0], SUMMER[0][1])
+    summer_end_date = date(added_date.year, SUMMER[1][0], SUMMER[1][1])
+    first_winter_start_date = date(added_date.year, WINTER[0][0], WINTER[0][1])
+    first_winter_end_date = date(added_date.year + 1, WINTER[1][0], WINTER[1][1])
+    second_winter_end_date = date(added_date.year, WINTER[1][0], WINTER[1][1])
+
+    # If we're in the middle of summer, add the days remaining of summer
+    if summer_start_date < added_date < summer_end_date:
+        expiry_date += timedelta(days=(summer_end_date - added_date).days)
+    # If the number of days between added_date and the beginning of summer vacation is less
+    # than the duration, we need to add the length of summer to the expiry date
+    elif 0 < (summer_start_date - added_date).days < DURATION:
+        expiry_date += timedelta(days=(summer_end_date - summer_start_date).days)
+    # Same for middle of winter vacation, which will be at the end of the year
+    elif first_winter_start_date < added_date < first_winter_end_date:
+        expiry_date += timedelta(days=(first_winter_end_date - added_date).days)
+    # And for before the vacation
+    elif 0 < (first_winter_start_date - added_date).days < DURATION:
+        expiry_date += timedelta(days=(first_winter_end_date - first_winter_start_date).days)
+    # Then we need to check the edge case where now is between newyears and and of winter vacation
+    elif second_winter_end_date > added_date:
+        expiry_date += timedelta(days=(second_winter_end_date - added_date).days)
+
+    # The returned value is a timezone aware datetime object
+    return timezone.make_aware(datetime.combine(expiry_date, time()), timezone.get_current_timezone())
diff --git a/apps/mommy/__init__.py b/apps/mommy/__init__.py
--- a/apps/mommy/__init__.py
+++ b/apps/mommy/__init__.py
@@ -6,6 +6,8 @@
 logger = logging.getLogger(__name__)
 #logger.addHandler(logging.NullHandler)  # logg to /dev/null if no other handler
 
+from django.conf import settings
+
 schedule = Schedule()
 
 def autodiscover():
@@ -31,11 +33,12 @@ def run():
     """
     imports apscheduler, registers scheduled jobs, runs the scheduler
     """
-    from apscheduler.scheduler import Scheduler
+    if settings.FEEDBACK_MAIL_SCHEDULER:
+        from apscheduler.scheduler import Scheduler
 
-    # Start the scheduler
-    sched = Scheduler()
-    sched.start()
+        # Start the scheduler
+        sched = Scheduler()
+        sched.start()
 
-    for task, kwargs in schedule.tasks.iteritems():
-       sched.add_cron_job(task.run, name=task.__name__, **kwargs)
+        for task, kwargs in schedule.tasks.iteritems():
+            sched.add_cron_job(task.run, name=task.__name__, **kwargs)


Test patch:
diff --git a/apps/marks/tests.py b/apps/marks/tests.py
--- a/apps/marks/tests.py
+++ b/apps/marks/tests.py
@@ -1,28 +1,72 @@
+from datetime import datetime, time, timedelta
 import logging
 
 from django_dynamic_fixture import G
+from django.utils import timezone
 from django.test import TestCase
 
 from apps.authentication.models import OnlineUser as User
 from apps.marks.models import Mark, UserEntry
+from apps.marks.models import _get_expiration_date
 
 class MarksTest(TestCase):
 
     def setUp(self):
+        self.logger = logging.getLogger(__name__)
         self.user=G(User)
-        #Mark added 59 (working) days ago.
-        self.mark = G(Mark, title="1")
+        self.mark = G(Mark, title="Testprikk", added_date=timezone.now())
         self.userentry = G(UserEntry, user=self.user)
-        self.logger = logging.getLogger(__name__)
 
     def testMarksActive(self):
-        self.logger.debug("Testing if Mark is active today with dynamic fixtures")
+        self.logger.debug("Testing if Mark is active")
         self.assertTrue(self.mark.is_active)
         
     def testMarkUnicode(self):    
         self.logger.debug("Testing Mark unicode with dynamic fixtures")
-        self.assertEqual(self.mark.__unicode__(), "Prikk for 1")
+        self.assertEqual(unicode(self.mark), u"Prikk for Testprikk")
         
     def testUserEntry(self):
         self.logger.debug("Testing UserEntry unicode with dynamic fixtures")
-        self.assertEqual(self.userentry.__unicode__(), ("UserEntry for %s") % self.user.get_full_name())
\ No newline at end of file
+        self.assertEqual(unicode(self.userentry), ("UserEntry for %s") % self.user.get_full_name())
+
+    def testGettingExpirationDateWithNoVacationInSpring(self):
+        self.logger.debug("Testing expiration date with no vacation span in the spring")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 2, 1), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2013, 4, 2), time()), timezone.get_current_timezone()), prikk.expiration_date)
+
+    def testGettingExpirationDateWithSummerVacation(self):
+        self.logger.debug("Testing expiration date with the summer vacation span")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 5, 1), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2013, 9, 13), time()), timezone.get_current_timezone()), prikk.expiration_date)
+
+    def testGettingExpirationDateWithNoVacationInFall(self):
+        self.logger.debug("Testing expiration date with no vacation span in the spring")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 9, 1), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2013, 10, 31), time()), timezone.get_current_timezone()), prikk.expiration_date)
+
+    def testGettingExpirationDateWithWinterVacation(self):
+        self.logger.debug("Testing expiration date with the summer vacation span")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 11, 1), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2014, 2, 14), time()), timezone.get_current_timezone()), prikk.expiration_date)
+
+    def testGettingExpirationDateWhenDateBetweenNewYearsAndEndOfWinterVacation(self):
+        self.logger.debug("Testing expiration date with no vacation span in the spring")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 1, 1), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2013, 3, 16), time()), timezone.get_current_timezone()), prikk.expiration_date)
+
+    def testGettingExpirationDateWhenDateBetweenStartOfWinterVacationAndNewYears(self):
+        self.logger.debug("Testing expiration date with no vacation span in the spring")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 12, 15), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2014, 3, 16), time()), timezone.get_current_timezone()), prikk.expiration_date)
+
+    def testGettingExpirationDateWhenDateInSummerVacation(self):
+        self.logger.debug("Testing expiration date with no vacation span in the spring")
+        date = timezone.make_aware(datetime.combine(datetime(2013, 7, 1), time()), timezone.get_current_timezone())
+        prikk = G(Mark, added_date=date)
+        self.assertEqual(timezone.make_aware(datetime.combine(datetime(2013, 10, 14), time()), timezone.get_current_timezone()), prikk.expiration_date)