# Path: django_ratings/models.py
# class TotalRate(models.Model):
#     """
#     save all rating for individual object.
#     """
#     target_ct = models.ForeignKey(ContentType, db_index=True)
#     target_id = models.PositiveIntegerField(_('Object ID'))
#     target = generic.GenericForeignKey('target_ct', 'target_id')
#     amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2)
# 
#     objects = TotalRateManager()
# 
#     def __unicode__(self):
#         return u'%s points for %s' % (self.amount, self.target)
# 
#     class Meta:
#         verbose_name = _('Total rate')
#         verbose_name_plural = _('Total rates')
#         unique_together = (('target_ct', 'target_id',),)
# 
# class Rating(models.Model):
#     """
#     Rating of an object.
#     """
#     target_ct = models.ForeignKey(ContentType, db_index=True)
#     target_id = models.PositiveIntegerField(_('Object ID'), db_index=True)
#     target = generic.GenericForeignKey('target_ct', 'target_id')
# 
#     time = models.DateTimeField(_('Time'), default=datetime.now, editable=False)
#     user = models.ForeignKey(User, blank=True, null=True)
#     amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2)
#     ip_address = models.CharField(_('IP Address'), max_length="15", blank=True)
# 
#     objects = RatingManager()
# 
#     def __unicode__(self):
#         return u'%s points for %s' % (self.amount, self.target)
# 
#     class Meta:
#         verbose_name = _('Rating')
#         verbose_name_plural = _('Ratings')
# 
#     def save(self, **kwargs):
#         """
#         Modified save() method that checks for duplicit entries.
#         """
#         if not self.pk:
#             # fail silently on inserting duplicate ratings
#             if self.user:
#                 try:
#                     Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user)
#                     return
#                 except Rating.DoesNotExist:
#                     pass
#             elif (self.ip_address and Rating.objects.filter(
#                         target_ct=self.target_ct,
#                         target_id=self.target_id,
#                         user__isnull=True,
#                         ip_address=self.ip_address ,
#                         time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY)
#                     ).count() > 0):
#                 return
#             # denormalize the total rate
#             cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount)
#             if cnt == 0:
#                 tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount)
# 
# 
#         super(Rating, self).save(**kwargs)
# 
# class Agg(models.Model):
#     """
#     Aggregation of rating objects.
#     """
#     target_ct = models.ForeignKey(ContentType, db_index=True)
#     target_id = models.PositiveIntegerField(_('Object ID'), db_index=True)
#     target = generic.GenericForeignKey('target_ct', 'target_id')
# 
#     time = models.DateField(_('Time'))
#     people = models.IntegerField(_('People'))
#     amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2)
#     period = models.CharField(_('Period'), max_length="1", choices=PERIOD_CHOICES)
#     detract = models.IntegerField(_('Detract'), default=0, max_length=1)
# 
#     objects = AggManager()
# 
#     def __unicode__(self):
#         return u'%s points for %s' % (self.amount, self.target)
# 
#     class Meta:
#         verbose_name = _('Aggregation')
#         verbose_name_plural = _('Aggregations')
#         ordering = ('-time',)
# 
# Path: django_ratings/aggregation.py
# def transfer_data():
#     """
#     transfer data from table Rating to table Agg
#     """
#     logger.info("transfer_data BEGIN")
#     timenow = datetime.now()
#     for t in sorted(TIMES_ALL.keys(), reverse=True):
#         TIME_DELTA = t
#         time_agg = timenow - timedelta(seconds=TIME_DELTA)
#         Rating.objects.move_rate_to_agg(time_agg, TIMES_ALL[t])
#     transfer_agg_to_agg()
#     transfer_agg_to_totalrate()
#     logger.info("transfer_data END")


from datetime import date, timedelta, datetime
from django_ratings.models import TotalRate, Rating, Agg
from django_ratings.aggregation import transfer_data
from helpers import SimpleRateTestCase



class TestAggregation(SimpleRateTestCase):
    def test_totalrate_from_aggregation(self):
        now = date.today()
        for i in range(1,4):
            Agg.objects.create(people=i, amount=4-i, time=now, period='d', detract=0, **self.kw)
        Agg.objects.agg_to_totalrate()

# Path: django_ratings/models.py
# class TotalRate(models.Model):
#     """
#     save all rating for individual object.
#     """
#     target_ct = models.ForeignKey(ContentType, db_index=True)
#     target_id = models.PositiveIntegerField(_('Object ID'))
#     target = generic.GenericForeignKey('target_ct', 'target_id')
#     amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2)
# 
#     objects = TotalRateManager()
# 
#     def __unicode__(self):
#         return u'%s points for %s' % (self.amount, self.target)
# 
#     class Meta:
#         verbose_name = _('Total rate')
#         verbose_name_plural = _('Total rates')
#         unique_together = (('target_ct', 'target_id',),)
# 
# class Rating(models.Model):
#     """
#     Rating of an object.
#     """
#     target_ct = models.ForeignKey(ContentType, db_index=True)
#     target_id = models.PositiveIntegerField(_('Object ID'), db_index=True)
#     target = generic.GenericForeignKey('target_ct', 'target_id')
# 
#     time = models.DateTimeField(_('Time'), default=datetime.now, editable=False)
#     user = models.ForeignKey(User, blank=True, null=True)
#     amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2)
#     ip_address = models.CharField(_('IP Address'), max_length="15", blank=True)
# 
#     objects = RatingManager()
# 
#     def __unicode__(self):
#         return u'%s points for %s' % (self.amount, self.target)
# 
#     class Meta:
#         verbose_name = _('Rating')
#         verbose_name_plural = _('Ratings')
# 
#     def save(self, **kwargs):
#         """
#         Modified save() method that checks for duplicit entries.
#         """
#         if not self.pk:
#             # fail silently on inserting duplicate ratings
#             if self.user:
#                 try:
#                     Rating.objects.get(target_ct=self.target_ct, target_id=self.target_id, user=self.user)
#                     return
#                 except Rating.DoesNotExist:
#                     pass
#             elif (self.ip_address and Rating.objects.filter(
#                         target_ct=self.target_ct,
#                         target_id=self.target_id,
#                         user__isnull=True,
#                         ip_address=self.ip_address ,
#                         time__gte=(self.time or datetime.now()) - timedelta(seconds=MINIMAL_ANONYMOUS_IP_DELAY)
#                     ).count() > 0):
#                 return
#             # denormalize the total rate
#             cnt = TotalRate.objects.filter(target_ct=self.target_ct, target_id=self.target_id).update(amount=models.F('amount')+self.amount)
#             if cnt == 0:
#                 tr = TotalRate.objects.create(target_ct=self.target_ct, target_id=self.target_id, amount=self.amount)
# 
# 
#         super(Rating, self).save(**kwargs)
# 
# class Agg(models.Model):
#     """
#     Aggregation of rating objects.
#     """
#     target_ct = models.ForeignKey(ContentType, db_index=True)
#     target_id = models.PositiveIntegerField(_('Object ID'), db_index=True)
#     target = generic.GenericForeignKey('target_ct', 'target_id')
# 
#     time = models.DateField(_('Time'))
#     people = models.IntegerField(_('People'))
#     amount = models.DecimalField(_('Amount'), max_digits=10, decimal_places=2)
#     period = models.CharField(_('Period'), max_length="1", choices=PERIOD_CHOICES)
#     detract = models.IntegerField(_('Detract'), default=0, max_length=1)
# 
#     objects = AggManager()
# 
#     def __unicode__(self):
#         return u'%s points for %s' % (self.amount, self.target)
# 
#     class Meta:
#         verbose_name = _('Aggregation')
#         verbose_name_plural = _('Aggregations')
#         ordering = ('-time',)
# 
# Path: django_ratings/aggregation.py
# def transfer_data():
#     """
#     transfer data from table Rating to table Agg
#     """
#     logger.info("transfer_data BEGIN")
#     timenow = datetime.now()
#     for t in sorted(TIMES_ALL.keys(), reverse=True):
#         TIME_DELTA = t
#         time_agg = timenow - timedelta(seconds=TIME_DELTA)
#         Rating.objects.move_rate_to_agg(time_agg, TIMES_ALL[t])
#     transfer_agg_to_agg()
#     transfer_agg_to_totalrate()
#     logger.info("transfer_data END")


# Path: tests/unit_project/test_aggregation.py
from datetime import date, timedelta, datetime
from django_ratings.models import TotalRate, Rating, Agg
from django_ratings.aggregation import transfer_data
from helpers import SimpleRateTestCase




class TestAggregation(SimpleRateTestCase):
    def test_totalrate_from_aggregation(self):
        now = date.today()
        for i in range(1,4):
            Agg.objects.create(people=i, amount=4-i, time=now, period='d', detract=0, **self.kw)
        Agg.objects.agg_to_totalrate()

        self.assert_equals(6, TotalRate.objects.get_for_object(self.obj))