def monthCalc(request):
    req = request.REQUEST
    if param_exist("date",req):
        date = DateService.parse(req['date'])
    else:
        date = DateService.today()

    fromDate = DateService.firstDateOfMonth(date)
    toDate = DateService.lastDateOfMonth(date)
    
    q = Expense.objects.extra(select={'sum': 'sum(amount)'}).values('sum','date')
    #q = Expense.objects.filter(date__gte=fromDate, date__lte=toDate)
    q = q.filter(date__gte=fromDate, date__lte=toDate).order_by('date')
    if param_exist("subC",req):
        q = q.filter(subCategory=req['subC'])
    elif param_exist("cat",req):
        c = SubCategory.objects.filter(category=req['cat'])
        q = q.filter(subCategory__in=c)
    if param_exist("payT",req):
        q = q.filter(paymentType=req['payT'])
    q.query.group_by = ['date']
    
    list = []
    for exp in q:
        list.append('[%d,%s]' % (int(DateService.toLong(exp['date'])),exp['sum']))
    
    data = "[" + ",".join(list) + "]"
    return data
def calc(request):
    req = request.REQUEST
    if param_exist("date",req):
        date = DateService.parse(req['date'])
    else:
        date = DateService.today()

    fromDate = DateService.firstDateOfMonth(date)
    toDate = DateService.lastDateOfMonth(date)
    
    q = Expense.objects.filter(date__gte=fromDate, date__lte=toDate)
    if param_exist("subC",req):
        q = q.filter(subCategory=req['subC'])
    elif param_exist("cat",req):
        c = SubCategory.objects.filter(category=req['cat'])
        q = q.filter(subCategory__in=c)
    if param_exist("payT",req):
        q = q.filter(paymentType=req['payT'])
        
    sum=0
    for exp in q:
        sum+=exp.amount
    
    today = DateService.today()
    if today.tm_year==date.tm_year and today.tm_mon==date.tm_mon:
        days=today.tm_mday
    else:
        days=DateService.lastDayOfMonth(date)

    avg = sum / days
    data = '{"data":{"total":%s,"avg":%s}}' % (sum,avg)
    return data
Example #3
0
def taxHome(request):
    # some stuff are resolved using python code instead of django queryset because limitations of appengine
    limit = (datetime.datetime.now() + datetime.timedelta(days=getattr(settings,'TAX_DEFAULT_DAYS_ADVANCE', 5)))
    upcoming = Tax.objects.filter(expire__lte=limit).order_by('expire')
    upcoming = [tax for tax in upcoming if tax.amount > 0]
    current = Tax.objects.filter(expire__range=(DateService.firstDateOfMonth(datetime.date.today()), DateService.lastDateOfMonth(datetime.date.today())))
    nextList = Tax.objects.filter(expire__range=DateService.getMonthDateRange(DateService.addMonth(DateService.todayDate(), 1)))
    return {"list": upcoming, "listmonth": sorted(current, key=lambda service: tax.service), "listnextmonth": sorted(nextList, key=lambda service: tax.service)}
Example #4
0
def generate():
    date = DateService.addMonth(DateService.todayDate(),-1) 
    fromDate = DateService.addMonth(DateService.firstDateOfMonth(date),-6)
    toDate = DateService.lastDateOfMonth(date)
    
    values = DateService.getMonthRange(fromDate, toDate)

    for value in values:
        create_stats(*value)
Example #5
0
def sixMonthCalc(request):
    req = request.REQUEST
    if param_exist("date",req):
        date = DateService.parse(req['date'])
    else:
        date = DateService.today()

    fromDate = DateService.addMonth(DateService.firstDateOfMonth(date),-6)
    toDate = DateService.lastDateOfMonth(date)
    
    query = "SELECT sum(amount), date FROM expense "\
            "WHERE date between '%s' and '%s'" % (str(fromDate), str(toDate))
    if param_exist("subC",req):
        query += " AND sub_category_id = '%s'" % req['subC']
    elif param_exist("cat",req):
        c = SubCategory.objects.filter(category=req['cat'])
        query += " AND sub_category_id in (%s)" % ",".join(["'"+str(s.id)+"'" for s in c])
    if param_exist("payT",req):
        query += " AND payment_type_id = '%s'" % req['payT']
    query += " group by month(date)"
    
    cursor = connection.cursor()
    cursor.execute(query)

    list = []
    for exp in cursor.fetchall():
        sum, date = exp
        i = Income.objects.extra(select={'sum': 'sum(amount)'}).values('sum')
        i = i.filter(period = DateService.firstDateOfMonth(date.timetuple()))
        val = i[0]['sum']
        if val is None:
            val = 0
        list.append({'date': date, 'expense': sum, 'income': val})

    data = '{"rows": %s}' % (JsonParser.parse(list))
    return data
Example #6
0
def report(request):
    if RequestUtils.param_exist("date", request.REQUEST):
        date = DateService.parseDate(request.REQUEST['date'])
    else:
        date = DateService.addMonth(DateService.todayDate(),-1)
    fromDate = DateService.midNight(DateService.firstDateOfMonth(date))
    toDate = DateService.midNight(DateService.lastDateOfMonth(date),True)
    try:
        q = Expense.objects.filter(date__gte=fromDate, date__lte=toDate)
        filedata = StringIO.StringIO()
        filedata.write('"pk","date","text","amount","paymentTypePk","paymentTypeName","categoryPk","categoryName","subCategoryPk","subCategoryName"\n')
        for expense in q:
            d = {'pk': expense.pk,
                'date': DateService.invert(expense.date),
                'text': expense.text,
                'amount': expense.amount,
                'paymentTypePk': expense.paymentType.pk,
                'paymentTypeName': expense.paymentType.name,
                'categoryPk': expense.subCategory.category.pk,
                'categoryName': expense.subCategory.category.name,
                'subCategoryPk': expense.subCategory.pk,
                'subCategoryName': expense.subCategory.name}
            filedata.write(smart_str('%(pk)s,%(date)s,"%(text)s",%(amount)s,%(paymentTypePk)s,"%(paymentTypeName)s",%(categoryPk)s,"%(categoryName)s",%(subCategoryPk)s,"%(subCategoryName)s"\n' % d, 'latin1'))
        
        filename = "expensereport_%s.csv" % fromDate.strftime("%Y%m")
        
        if RequestUtils.param_exist("gz", request.REQUEST):
            filezip = StringIO.StringIO()
            zipped = gzip.GzipFile(filename, 'wb', fileobj=filezip)
            zipped.write(filedata)
            zipped.close()
            st = StorageService()
            st.file_put(filezip.getvalue(), filename + ".gz")
        else:
            st = StorageService()
            st.file_put(filedata.getvalue(), filename)
        error = ''
    except Exception, e:
        logger.error(str(e))
        send_mail("EXPORT ERROR", 'Processing %s.\n\nError: %s' % (fromDate.strftime("%Y-%m"), str(e)))
        error=str(e)
Example #7
0
 def handle(self, *args, **options):
     list = Debits.objects.filter(Q(since__lte=datetime.now()) & (Q(last__isnull=True) | Q(last__lt=DateService.firstDateOfMonth(DateService.today()))))
     
     for debit in list:
         Expense.objects.create(text=debit.text,
                                amount=debit.amount,
                                subCategory=debit.subCategory,
                                paymentType=debit.paymentType,
                                date=DateService.invert(DateService.parse("%d/%d/%d" % (debit.day,
                                                                     DateService.today().tm_mon,
                                                                     DateService.today().tm_year))))
         debit.last = datetime.now()
         debit.save()
     
     self.stdout.write("Processed %d\n" % list.count())
Example #8
0
def generate_current():
    date = DateService.todayDate() 
    fromDate = DateService.firstDateOfMonth(date)
    toDate = DateService.lastDateOfMonth(date)
    create_stats(fromDate, toDate)