11import csv
22import logging
33import os
4+ import sys
45import tempfile
56from datetime import datetime , timedelta
67from optparse import make_option
78
9+ from lib .transactions import constants
810from lib .transactions .models import Transaction
911from solitude .management .commands .push_s3 import push
1012
1416log = logging .getLogger ('s.transactions' )
1517
1618
17- def generate_log (day , filename ):
19+ def generate_log (day , filename , log_type ):
1820 out = open (filename , 'w' )
1921 writer = csv .writer (out )
2022 next_day = day + timedelta (days = 1 )
2123 writer .writerow (('version' , 'uuid' , 'created' , 'modified' , 'amount' ,
2224 'currency' , 'status' , 'buyer' , 'seller' ))
25+
2326 transactions = Transaction .objects .filter (modified__range = (day , next_day ))
24- for transaction in transactions :
25- writer .writerow (transaction .for_log ())
27+
28+ if log_type == 'stats' :
29+ for row in transactions :
30+ row .log .get_or_create (type = constants .LOG_STATS )
31+ writer .writerow (row .for_log ())
32+
33+ if log_type == 'revenue' :
34+ transactions = transactions .filter (
35+ status__in = (constants .STATUS_COMPLETED , constants .STATUS_CHECKED ),
36+ log__type__isnull = True # Ignore already logged transactions.
37+ )
38+
39+ for row in transactions :
40+ obj , created = row .log .get_or_create (type = constants .LOG_REVENUE )
41+ if not created :
42+ # This should never happen, but just in case.
43+ print 'Transaction skipped: {0}' .format (row .uuid )
44+ continue
45+
46+ writer .writerow (row .for_log ())
2647
2748
2849class Command (BaseCommand ):
@@ -38,9 +59,18 @@ class Command(BaseCommand):
3859 option_list = BaseCommand .option_list + (
3960 make_option ('--date' , action = 'store' , type = 'string' , dest = 'date' ),
4061 make_option ('--dir' , action = 'store' , type = 'string' , dest = 'dir' ),
62+ make_option ('--type' , action = 'store' , type = 'string' , dest = 'log_type' ),
4163 )
4264
65+ types = ['stats' , 'revenue' ]
66+
4367 def handle (self , * args , ** options ):
68+ log_type = options ['log_type' ]
69+ if log_type not in self .types :
70+ msg = 'Type not valid, must be one of: %s' % self .types
71+ log .debug (msg )
72+ sys .exit (1 )
73+
4474 dir_ = not options ['dir' ]
4575 if dir_ :
4676 log .debug ('No directory specified, making temp.' )
@@ -49,8 +79,9 @@ def handle(self, *args, **options):
4979 yesterday = datetime .today () - timedelta (days = 1 )
5080 date = (datetime .strptime (options ['date' ], '%Y-%m-%d' )
5181 if options ['date' ] else yesterday ).date ()
52- filename = os .path .join (dir_ , date .strftime ('%Y-%m-%d' ) + '.log' )
53- generate_log (date , filename )
82+ filename = os .path .join (dir_ , '{0}.{1}.log' .format (
83+ date .strftime ('%Y-%m-%d' ), log_type ))
84+ generate_log (date , filename , log_type )
5485 log .debug ('Log generated to: %s' , filename )
5586 push (filename )
5687 if not options ['dir' ]:
0 commit comments