# Path: django_ratings/models.py
# 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',)
# 
# 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',),)


import logging
from datetime import datetime, timedelta
from django_ratings.models import Rating, Agg, TotalRate
"""
This file is for aggregation records from Rating,Agg tables to Agg and TotalRate table
"""



logger = logging.getLogger('django_ratings')

# aggregate ratings older than 2 years by year
DELTA_TIME_YEAR = 2*365*24*60*60
# ratings older than 2 months by month
DELTA_TIME_MONTH = 2*30*24*60*60
# rest of the ratings (last 2 months) aggregate daily
DELTA_TIME_DAY = -24*60*60

TIMES_ALL = {DELTA_TIME_YEAR : 'year', DELTA_TIME_MONTH : 'month', DELTA_TIME_DAY : 'day'}

def transfer_agg_to_totalrate():
    """
    Transfer aggregation data from table Agg to table TotalRate
    """
    logger.info("transfer_agg_to_totalrate BEGIN")

# Path: django_ratings/models.py
# 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',)
# 
# 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',),)


# Path: django_ratings/aggregation.py
import logging
from datetime import datetime, timedelta
from django_ratings.models import Rating, Agg, TotalRate

"""
This file is for aggregation records from Rating,Agg tables to Agg and TotalRate table
"""



logger = logging.getLogger('django_ratings')

# aggregate ratings older than 2 years by year
DELTA_TIME_YEAR = 2*365*24*60*60
# ratings older than 2 months by month
DELTA_TIME_MONTH = 2*30*24*60*60
# rest of the ratings (last 2 months) aggregate daily
DELTA_TIME_DAY = -24*60*60

TIMES_ALL = {DELTA_TIME_YEAR : 'year', DELTA_TIME_MONTH : 'month', DELTA_TIME_DAY : 'day'}

def transfer_agg_to_totalrate():
    """
    Transfer aggregation data from table Agg to table TotalRate
    """
    logger.info("transfer_agg_to_totalrate BEGIN")

    if TotalRate.objects.count() != 0: