import csv from pytz import utc import os from django.core.management.base import BaseCommand, CommandError from django.contrib.contenttypes.models import ContentType from apps.payment.tasks import transaction_to_roistat from apps.payment.models import Payment import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Send ' def add_arguments(self, parser): parser.add_argument( '--start_id', type=int, help='Start payment id', ) parser.add_argument( '--csv', dest='csv', help='CSV file with exist payments in roistat', ) def handle(self, *args, **options): start_id = options.get('start_id') csv_file = options.get('csv') if start_id: print('start_id=' + str(start_id)) payments = Payment.objects.filter(id__gte=start_id, status__in=Payment.PW_PAID_STATUSES) for payment in payments: print('TRANSACTION: ' + str(payment.id)) transaction_to_roistat.delay( payment.user.id, payment.id, f'School payment', payment.amount, payment.created_at.strftime('%Y-%m-%d %H:%M:%S'), 0, f'school', payment.roistat_visit, ) if csv_file: if not os.path.exists(csv_file): raise CommandError('File not found') content_types = dict(ContentType.objects.filter(app_label='payment').values_list('id', 'model')) with open(csv_file, encoding='utf-8') as csv_file: reader = csv.reader(csv_file, delimiter='\n') ids = [p[0] for p in reader] print('Payments in csv', len(ids)) payments = Payment.objects.exclude(id__in=ids) print('Other payments count', payments.count()) for payment in payments: content_type = content_types.get(payment.polymorphic_ctype_id, '') product_type = content_type[:content_type.find('payment')] if product_type == 'drawingcamp': product_type = 'drawing_camp' if product_type == 'giftcertificate': product_type = 'gift_certificate' event_name = '%s payment' % product_type.title() transaction_to_roistat.delay( payment.user.id, payment.id, event_name, payment.amount, payment.created_at.astimezone(utc).strftime('%Y-%m-%d %H:%M:%S'), 0, product_type, payment.roistat_visit, )