realize_payments.py 2.78 KB
#-*- coding:utf-8 -*-

#Copyright (c) 2012, Bartłomiej Nitoń
#All rights reserved.

#Redistribution and use in source and binary forms, with or without modification, are permitted provided 
#that the following conditions are met:

#    Redistributions of source code must retain the above copyright notice, this list of conditions and 
#    the following disclaimer.
#    Redistributions in binary form must reproduce the above copyright notice, this list of conditions 
#    and the following disclaimer in the documentation and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED 
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

import codecs

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

from accounts.models import RealizedLemma
from django.db.models import Sum

class Command(BaseCommand):
    args = 'none'
    help = """
    Mark realized lemmas as paid and add paid value to
    paid_cash field in UserStats model.
    """

    def handle(self, **options):
        realize_payments()

def realize_payments():
    payments_path = 'data/real_payments.csv'
    payments_file = codecs.open(payments_path, 'wt', 'utf-8')
    users = User.objects.all()
    for user in users:
        realized_lemmas = RealizedLemma.objects.filter(user_stats__user=user, 
                                                       paid=False,
                                                       date__range=["2010-01-01", 
                                                                    "2013-05-01"])
        cash_to_pay = realized_lemmas.aggregate(Sum('cash'))['cash__sum']
        if cash_to_pay:
            payments_file.write(u'Użytkownik' + ';' + user.username + ';' +
                                u'Wynagrodzenie' + ';' + str(round(cash_to_pay, 2)) + '\n')
            user.user_stats.paid_cash += cash_to_pay
            user.user_stats.save()
            for real_lemma in realized_lemmas:
                real_lemma.paid = True
                real_lemma.save()                                                                 
    payments_file.close()