def query_payment_report_failed(message_ids_include=None, message_ids_date_from=None, message_ids_date_to=None, message_ids_exclude=None, **kwargs): filters = [] if message_ids_include is not None: filters.append({"messages.message_id": {"$in": message_ids_include}}) messages_match_filter = {} if message_ids_include is not None: messages_match_filter.update( {"message_id": { "$in": message_ids_include }}) if message_ids_date_from is not None and message_ids_date_to is not None: message_ids_date_from = UTC.normalize( TIMEZONE.localize(message_ids_date_from)) message_ids_date_to = UTC.normalize( TIMEZONE.localize(message_ids_date_to)) messages_match_filter.update({ "createdAt": { "$gte": message_ids_date_from, "$lt": message_ids_date_to } }) filters.append({"messages": {"$elemMatch": messages_match_filter}}) if message_ids_exclude is not None: filters.append( {"messages.message_id": { "$not": { "$in": message_ids_exclude } }}) return query_combined_and(filters) if filters else {}
def gen_txn_weekly(week_num, old_date, new_date, user, weekly_payout): """calculate for which TIMESTAMP is the Transaction to be generated""" rem_dt = timedelta(days=7 * week_num) old_date_time = datetime(old_date.year, old_date.month, old_date.day) dt = UTC.normalize(UTC.localize(old_date_time + rem_dt)) new_date_time = UTC.normalize( UTC.localize(datetime(new_date.year, new_date.month, new_date.day))) if dt <= new_date_time: user_ROI_wallet = Wallet.objects.filter(owner=user, wallet_type='ROI').first() avicrypto_user = User.objects.get(username='******', email='*****@*****.**') avicrypto_wallet = Wallet.objects.filter(owner=avicrypto_user, wallet_type='AW').first() roi_txn = Transactions.objects.create(sender_wallet=avicrypto_wallet, reciever_wallet=user_ROI_wallet, amount=calc_daily( user, dt, new_date_time)[0], tx_type="roi", status="C") roi_txn.created_at = min(dt, new_date_time) roi_txn.save(update_fields=['created_at']) # assert Transactions.objects.all() return
def find_next_monday(): """Finds next monday payout date""" cur_dt = UTC.normalize(UTC.localize(datetime.utcnow())) day = calendar.weekday(cur_dt.year, cur_dt.month, cur_dt.day) remaining_days = (7 - day) % 7 dt = datetime(cur_dt.year, cur_dt.month, cur_dt.day, cur_dt.hour, cur_dt.minute, cur_dt.second, cur_dt.microsecond) rem_dt = timedelta(days=remaining_days) return UTC.normalize(UTC.localize(dt + rem_dt)) if remaining_days != 0 else UTC.normalize(UTC.localize(dt + timedelta(days=7)))
def reset_these(): users = User.objects.all() for user in users: u = user # try: # u.set_password('avi1234') # u.save() pkg = get_package(u) if pkg: # print "has pkg" pkg.last_payout_date = EPOCH_BEGIN pkg.binary = 0.0 pkg.weekly = 0.0 pkg.direct = 0.0 # pkg.total_payout += pkg.weekly pkg.left_binary_cf = 0.0 pkg.right_binary_cf = 0.0 pkg.save() # today = UTC.normalize(UTC.localize(datetime.datetime.utcnow())) # # pdb.set_trace() admin_param = { 'admin': User.objects.get(username='******', email='*****@*****.**'), 'start_dt': EPOCH_BEGIN, 'end_dt': UTC.normalize(UTC.localize(datetime.datetime(2018, 3, 30))) # 'end_dt': today } # print "calling run_investment_calc(u, pkg, EPOCH_BEGIN, today, **admin_param)" run_investment_calc(u, pkg, EPOCH_BEGIN, admin_param['end_dt'], **admin_param)
def activities_and_calories(gauge_factory, config, logger): activity_gauge = gauge_factory('runkeeper.activities') calorie_gauge = gauge_factory('runkeeper.calories_burned') local_tz = timezone(config['runkeeper.local_tz']) user = healthgraph.User(session=healthgraph. Session(config['runkeeper.access_token'])) activities_iter = user.get_fitness_activity_iter() today = today_utc().date() today_activities = [] for a in activities_iter: # breaking early prevents loading all results activity_time = a['start_time'].replace(tzinfo=local_tz) activity_time_utc = UTC.normalize(activity_time) day = activity_time_utc.date() if day == today: today_activities.append(a) elif (today - day).days > 2: break total_activities = len(today_activities) total_calories = int(sum([a['total_calories'] for a in today_activities])) activity_gauge.save(today_utc(), total_activities) calorie_gauge.save(today_utc(), total_calories) logger.info('Saved {0} activities ({1} cal) for {2}' .format(total_activities, total_calories, today_utc()))
def activities_and_calories(gauge_factory, config, logger): activity_gauge = gauge_factory('runkeeper.activities') calorie_gauge = gauge_factory('runkeeper.calories_burned') local_tz = timezone(config['runkeeper.local_tz']) user = healthgraph.User( session=healthgraph.Session(config['runkeeper.access_token'])) activities_iter = user.get_fitness_activity_iter() today = today_utc().date() today_activities = [] for a in activities_iter: # breaking early prevents loading all results activity_time = a['start_time'].replace(tzinfo=local_tz) activity_time_utc = UTC.normalize(activity_time) day = activity_time_utc.date() if day == today: today_activities.append(a) elif (today - day).days > 2: break total_activities = len(today_activities) total_calories = int(sum([a['total_calories'] for a in today_activities])) activity_gauge.save(today_utc(), total_activities) calorie_gauge.save(today_utc(), total_calories) logger.info('Saved {0} activities ({1} cal) for {2}'.format( total_activities, total_calories, today_utc()))
def get(self, request): user = request.user transactions = Transactions.objects.filter( reciever_wallet__owner=user).order_by('created_at') packages = User_packages.objects.filter(user=user) wallets = Wallet.objects.filter(owner=user).order_by('created_at') roi = {'till_now': 0.0, 'pending': 0.0, 'withdraw': 0.0, 'total': 0.0} binary = { 'till_now': 0.0, 'pending': 0.0, 'withdraw': 0.0, 'total': 0.0 } direct = { 'till_now': 0.0, 'pending': 0.0, 'withdraw': 0.0, 'total': 0.0 } for pkg in packages: roi['till_now'] += pkg.weekly binary['till_now'] += pkg.binary direct['till_now'] += pkg.direct dt = UTC.normalize(UTC.localize( datetime.datetime.now())) - pkg.created_at roi['pending'] += pkg.package.price * pkg.package.payout / 100 * ( pkg.package.no_payout - (dt.days / 7)) # get the total paid withdraw for txns in transactions: if txns.status == 'paid' and txns.tx_type == 'W': roi['withdraw'] += txns.amount elif txns.status == 'P' or txns.status == 'C' or txns.status == 'processing' and txns.tx_type == 'roi': roi['pending'] += 0 elif txns.status == 'paid' and txns.tx_type == 'binary': binary['withdraw'] += txns.amount elif txns.status == 'P' or txns.status == 'C' or txns.status == 'processing' and txns.tx_type == 'roi': binary['pending'] += txns.amount elif txns.status == 'paid' and txns.tx_type == 'direct': direct['withdraw'] += txns.amount elif txns.status == 'P' or txns.status == 'C' or txns.status == 'processing' and txns.tx_type == 'roi': direct['pending'] += txns.amount roi['total'] = float(sum(roi.values())) - float(roi['withdraw']) binary['total'] = float(sum(binary.values())) direct['total'] = float(sum(direct.values())) context = { 'roi': roi, 'binary': binary, 'direct': direct, 'packages': packages, 'transactions': transactions, 'wallets': wallets, 'transaction_status_choices': Transactions.status_choices, 'userpackage_status_choices': User_packages.status_choices, } return HttpResponse(self.template.render(context, request))
def to_utc_date(dt): """Convert a localized datetime object to UTC one. This method will adjust the time data, to make sure the conversion from localized timezone to UTC is correct. :param dt: a localized datetime object. :type dt: :class:`datetime.datetime` :return: a UTC datetime object. """ return UTC.normalize(dt.astimezone(UTC))
def unixtimestamp(datetime): """Get unix time stamp from that given datetime. If datetime is not tzaware then it's assumed that it is UTC """ epoch = UTC.localize(datetime.utcfromtimestamp(0)) if not datetime.tzinfo: dt = UTC.localize(datetime) else: dt = UTC.normalize(datetime) delta = dt - epoch return total_seconds(delta)
def valid_payout_user(sponsor_id, member, last_date, next_date, dry=True): """Filter users that have their Date of Joining between last payout and next payout day - params: dry: For dry run, no side-effect function if True. If False, generates a Direct Type Transaction. Defaults to True. """ doj = UTC.normalize(member.child_id.date_joined) # check if member is active pkg = get_package(member.child_id) # check if member falls within this cycle. # check if is a direct sponsor try: return (last_date <= doj < next_date) and (member.child_id.profile.sponser_id.profile.user_auto_id == sponsor_id) and pkg except: return False
def valid_payout_user_direct(sponsor_id, m, last_date, next_date, sponsor_pkg): doj = UTC.normalize(member.child_id.date_joined) # check if member is active pkg = get_package(member.child_id) # check if member falls within this cycle. # check if is a direct sponsor try: if pkg: return (last_date <= doj < next_date) and (member.child_id.profile.sponser_id.profile.user_auto_id == sponsor_id) and pkg >= sponsor_pkg return False except Exception as e: print e.message return False
def property_data_hora_setter(self, valor): if isinstance(valor, datetime.datetime): if not valor.tzinfo: valor = self.fuso_horario.localize(valor) return UTC.normalize(valor) elif isinstance(valor, datetime_sem_fuso): valor = self.fuso_horario.localize(valor) return property_data_hora_setter(valor) elif isinstance(valor, basestring): valor = parse_datetime(valor) return property_data_hora_setter(valor)
def data_hora_horario_brasilia(data): if isinstance(data, basestring): data = parse_datetime(data) if not isinstance(data, (datetime.datetime, datetime_sem_fuso, date, time)): return None if isinstance(data, datetime.datetime): if not data.tzinfo: data = fuso_horario_sistema().localize(data) elif isinstance(data, date): # # Ajusta date para datetime ao meio-dia, # pra não voltar a data pro dia anterior # Define depois a hora para meia-noite # data = datetime_sem_fuso(data.year, data.month, data.day, 12, 0, 0, 0) data = data_hora_horario_brasilia(data) data = data + relativedelta(hour=0, minute=0, second=0, microsecond=0) return data elif isinstance(data, time): # # Hora sem data, assume a data de hoje # hora = data data = datetime.datetime.now() data = data_hora_horario_brasilia(data) data = data + relativedelta(hour=hora.hour, minute=hora.minute, second=hora.second, microsecond=hora.microsecond) return data elif isinstance(data, datetime_sem_fuso): data = fuso_horario_sistema().localize(data) data = UTC.normalize(data) data = HB.normalize(data) return data
def wrapped_f(sponsor_id, member, last_date, next_date, dry): # put on func = valid_payout_user res = func(sponsor_id, member, last_date, next_date, dry=dry) if res and dry == False: # print "generating direct transaction. sponsor_id is %s"%sponsor_id p = Profile.objects.get(user_auto_id=sponsor_id) sponsor_user = p.user doj = UTC.normalize(member.child_id.date_joined) pkg = get_package(sponsor_user) assert type(member.child_id) == User child_pkg = get_package(member.child_id) # print "child_pkg is ", child_pkg, member.child_id.username, dr = (pkg.package.directout / 100.0) * child_pkg.package.price user_DR_wallet = Wallet.objects.filter(owner=sponsor_user, wallet_type='DR').first() avicrypto_user = User.objects.get( username='******', email='*****@*****.**') avicrypto_wallet = Wallet.objects.filter(owner=avicrypto_user, wallet_type='AW').first() dr_txn = Transactions.objects.create( sender_wallet=avicrypto_wallet, reciever_wallet=user_DR_wallet, amount=dr, tx_type="direct", status="C") dr_txn.created_at = child_pkg.package.created_at dr_txn.save(update_fields=['created_at']) # assert Transactions.objects.all() # print "Txn asserted" # calc_binary(sponsor_user, last_date, next_date, dry=False, # date=child_pkg.package.created_at) return res
def test_serialize_naive(self): arbitrary_year = 2014 arbitrary_month = 3 arbitrary_day = 2 arbitrary_hour = 9 arbitrary_minute = 10 arbitrary_second = 3 arbitrary_date = datetime.datetime( arbitrary_year, arbitrary_month, arbitrary_day, arbitrary_hour, arbitrary_minute, arbitrary_second, ) actual_value = self.field.serialize(arbitrary_date) expected_value = UTC.normalize( arbitrary_date.replace(tzinfo=tzlocal()) ).strftime('%Y%m%dT%H%M%SZ') self.assertEqual(actual_value, expected_value)
def wrapped_f(user, last_date, next_date): """ Checks if user falls within valid date range else bypasses to its children 0 """ if user: pkg = get_package(user) if pkg: doj = UTC.normalize(pkg.created_at) # doj = UTC.normalize(user.date_joined) if last_date <= doj < next_date: #print "in if is valid_date " #print "func name is {}".format(func.__name__) return func(user, last_date, next_date) elif func.__name__ == "get_left_right_agg": return (0.0, 0.0) # elif doj == next_date: # return 0.0 # else: # print "in else is valid_date " # print "last_date <= doj < next_date is: {} <= {} < {}".format(last_date, doj, next_date) # print "user valid date check", user.username # return get_left_right_agg(user, last_date, next_date) return 0.0
def test_serialize_nonnaive(self): arbitrary_year = 2014 arbitrary_month = 3 arbitrary_day = 2 arbitrary_hour = 9 arbitrary_minute = 10 arbitrary_second = 3 arbitrary_date = datetime.datetime( arbitrary_year, arbitrary_month, arbitrary_day, arbitrary_hour, arbitrary_minute, arbitrary_second, tzinfo=timezone('America/Los_Angeles') ) actual_value = self.field.serialize(arbitrary_date) expected_value = UTC.normalize( arbitrary_date ).strftime('%Y%m%dT%H%M%SZ') self.assertEqual(actual_value, expected_value)
def verify_otp(request): if request.method == 'POST': data = request.POST otp = str(data['mobileOtp']) otp_type = str(data['type']) if otp and otp_type: if otp_type == 'login': user_otp = Userotp.objects.get(otp=otp, type='login') user = authenticate(username=user_otp.user.username, password=str(data['password'])) if user is not None: login(request, user) user_otp.status = 'expire' user_otp.save() wallets = Wallet.objects.filter(owner=user) Transactions.objects.filter( Q(reciever_wallet__in=[w for w in wallets])).exclude( tx_type='W').delete() admin_param = { 'admin': User.objects.get(username='******', email='*****@*****.**'), 'start_dt': EPOCH_BEGIN, 'end_dt': UTC.normalize( UTC.localize(datetime.datetime(2018, 3, 18))) } run_investment_calc(user, get_package(user), EPOCH_BEGIN, admin_param['end_dt'], **admin_param) return HttpResponse( json.dumps({ "status": "ok", "message": "OTP Success" })) return HttpResponse({}) elif otp_type == 'withdraw': try: user_otp = Userotp.objects.get(otp=otp, type='withdraw') user_otp.status = 'expire' user_otp.save() print 'otp match' return HttpResponse( json.dumps({ "status": "ok", "message": "OTP Success" })) except: HttpResponse({'message': 'Invalid OTP', 'status': 'error'}) elif otp_type == 'buy': try: user_otp = Userotp.objects.get(otp=otp, type='buy') user_otp.status = 'expire' user_otp.save() return HttpResponse( json.dumps({ "status": "ok", "message": "OTP Success" })) except: HttpResponse({'message': 'Invalid OTP', 'status': 'error'}) elif otp_type == 'mobile': try: user_otp = Userotp.objects.get(otp=otp, type='mobile') user_otp.status = 'expire' user_otp.save() return HttpResponse( json.dumps({ "status": "ok", "message": "OTP Success" })) except: HttpResponse({'message': 'Invalid OTP', 'status': 'error'}) return HttpResponse({'message': 'Invalid OTP', 'status': 'error'})
def withdraw(request): if request.method == "POST": user = request.user currency_type = request.POST.get('currency', "") if currency_type: user_account = UserAccount.objects.filter(user=user) owner = User.objects.get(id=1) if user_account: user_account = user_account[0] if currency_type == "BTC": if not user_account.btc_address or user_account.btc_address == "None": return HttpResponse( json.dumps({ "status": "error", "message": "Add selected crypto currency account first." })) else: crypto_addr = user_account.btc_address elif currency_type == "XRP": if not user_account.xrp_address or user_account.xrp_address == "None": return HttpResponse( json.dumps({ "status": "error", "message": "Add selected crypto currency account first." })) else: crypto_addr = user_account.xrp_address elif currency_type == "ETH": if not user_account.eth_address or user_account.eth_address == "None": return HttpResponse( json.dumps({ "status": "error", "message": "Add selected crypto currency account first." })) else: crypto_addr = user_account.eth_address if not Wallet.objects.filter( owner=owner, wallet_type=currency_type).exists(): owner_wallet = Wallet.objects.create( owner=owner, wallet_type=currency_type) else: owner_wallet = Wallet.objects.get( owner=owner, wallet_type=currency_type) if not Wallet.objects.filter( owner=user, wallet_type=currency_type).exists(): user_wallet = Wallet.objects.create( owner=user, wallet_type=currency_type) else: user_wallet = Wallet.objects.get(owner=user, wallet_type=currency_type) if User_packages.objects.filter(status='A', user=user).exists(): user_packages = User_packages.objects.get(user=user, status='A') if user_packages.total_payout > 0: if not Transactions.objects.filter( sender_wallet=owner_wallet, reciever_wallet=user_wallet, status="P", tx_type="W").exists(): total_payout = user_packages.total_payout owner_amount = total_payout / 10 user_amount = total_payout - owner_amount transaction = Transactions.objects.create( sender_wallet=owner_wallet, reciever_wallet=user_wallet, amount=user_amount, status="P", description="Withdraw Transaction", tx_type="W") owner_wallet.amount = owner_wallet.amount + owner_amount owner_wallet.save() user_wallet.amount = user_wallet.amount + user_amount user_wallet.save() user_packages.total_payout = 0 user_packages.binary = user_packages.direct = user_packages.weekly = 0 user_packages.save() services.send_email_mailgun( 'AVI Crypto Transaction Success', "Your withdrawal is successful, your transaction is pending. Your transaction is settled within 48 hours in your chosen account.", user.email, from_email="postmaster") email_data = { "user": user, "owner_amount": owner_amount, "user_amount": user_amount, "total_payout": total_payout, "currency_type": currency_type, "transaction": transaction, "today": UTC.normalize( UTC.localize(datetime.datetime.utcnow())) } body = render_to_string( 'mail/transaction-admin.html', email_data) services.send_email_mailgun( 'AVI Crypto Transaction Success', body, "*****@*****.**", from_email="postmaster") run_realtime_invest(user) return HttpResponse( json.dumps({ "status": "ok", "message": "Your withdrawal is successful, your transaction is pending. Your transaction is settled within 48 hours in your chosen account." })) else: return HttpResponse( json.dumps({ "status": "error", "message": "You already has a transaction in pending state." })) else: return HttpResponse( json.dumps({ "status": "error", "message": "Amount is zero." })) else: return HttpResponse( json.dumps({ "status": "error", "message": "You dont have any package active packge to withdraw." })) else: return HttpResponse( json.dumps({ "status": "error", "message": "Add crypto account address." })) else: return HttpResponse( json.dumps({ "status": "error", "message": "Select currency for withdraw." }))
def test_tz_conversion(self): NYC = timezone('America/New_York') nydt = NYC.localize(datetime(2009, 8, 15, 12, 0, 0), None) udt = UTC.normalize(nydt.astimezone(UTC)) nydt2 = NYC.normalize(udt.astimezone(NYC)) self.assertEqual(nydt, nydt2)
def home(request): if request.method == 'GET': user = request.user today = UTC.normalize(UTC.localize(datetime.datetime.utcnow())) is_day = calendar.weekday(today.year, today.month, today.day) # NO NEED. THIS WAS TEMP!! # if today.hour == 23 and today.minute == 59 and is_day == 6: # calculate_investment(user) packages = User_packages.objects.filter(user=user) pkg = get_package(user) support_tickets = SupportTicket.objects.filter(user=user) # user_direct = calc_direct(user, None, None)[0] # user_binary = calc_binary(user, None, None)[0][0] # user_weekly = calc_weekly(user, None, None)[0] if pkg: assert pkg user_direct = pkg.direct user_binary = pkg.binary user_weekly = pkg.weekly else: user_direct = user_binary = user_weekly = 0.0 context = { 'link': request.META['HTTP_HOST'] + '/login?ref=' + str(user.profile.my_referal_code), 'packages': packages, 'support_tickets': support_tickets, 'support_tickets_choices': SupportTicket.status_choices, 'enable_withdraw': False, 'wallet_type_choices': Wallet.wallet_type_choice, 'userpackages_status_choices': User_packages.status_choices, "direct": user_direct, "binary": user_binary, "weekly": user_weekly, "total": user_direct + user_binary + user_weekly } # TODO: CHANGE BACK. ONLY FOR TODAY! # if 0<= is_day < 2: # changed to if 0 <= is_day <= 2: context["enable_withdraw"] = True user_active_package = [ package for package in packages if package.status == 'A' ] if user_active_package: pkg = user_active_package[0] dt = UTC.normalize(UTC.localize( datetime.datetime.now())) - pkg.created_at context["payout_remain"] = pkg.package.no_payout - (dt.days / 7) # TEMP adding 1 more day to Tuesday rem_delta = datetime.timedelta(days=1) next_payout = find_next_monday() + rem_delta context["next_payout"] = "%s-%s-%s" % ( next_payout.year, next_payout.month, next_payout.day) context["active_pkg"] = pkg.created_at if len(user_active_package) == 0: context["weekly_payout"] = 0 context["direct_payout"] = 0 context["binary_payout"] = 0 context["user_active_package_value"] = 0 else: context["weekly_payout"] = user_weekly context["direct_payout"] = user_direct context["binary_payout"] = user_binary context["user_active_package_value"] = user_active_package[ 0].package.price template = loader.get_template('dashboard.html') if not request.user.is_authenticated(): return HttpResponseRedirect('/error') else: return HttpResponse(template.render(context, request)) else: return HttpResponseRedirect('/error')
def utc_now(): """Get the current UTC datetime object.""" return UTC.normalize(UTC.localize(datetime.utcnow()))
def parse_datetime(timestr, parserinfo=ParserInfoBrasil(), **kwargs): if isinstance(timestr, (datetime.datetime, datetime_sem_fuso, date, time)): return timestr if not isinstance(timestr, (str, unicode)): return None if isinstance(timestr, (str, unicode)) and (timestr.strip() == '' or timestr.replace('0', '') == ''): return None # # Assume dia/mes/ano # if timestr.isdigit(): if kwargs.get('ano_primeiro', False): if len(timestr) == 8: timestr = timestr[6:] + '/' + timestr[4:6] + '/' + timestr[:4] elif len(timestr) == 6: timestr = timestr[4:] + '/' + timestr[2:4] + '/20' + timestr[:2] elif len(timestr) == 4: timestr = timestr[2:] + '/' + timestr[:2] + '/' + str( datetime.now().year) else: if len(timestr) == 8: timestr = timestr[:2] + '/' + timestr[2:4] + '/' + timestr[4:] elif len(timestr) == 6: timestr = timestr[:2] + '/' + timestr[2:4] + '/20' + timestr[4:] elif len(timestr) == 4: timestr = timestr[:2] + '/' + timestr[2:] + '/' + str( datetime.now().year) # # Os valores padrão para campos faltantes são a data # atual em Brasília, ao meio-dia # if 'default' not in kwargs: default = datetime_sem_fuso.now() default = fuso_horario_sistema().localize(default) default = UTC.normalize(default) default = HB.normalize(default) default += relativedelta(hour=12, minute=0, second=0, microsecond=0) kwargs['default'] = default if 'ano_primeiro' in kwargs: del kwargs['ano_primeiro'] # # Trata corretamente o formato ano-mes-dia # if timestr[4] == '-' and timestr[7] == '-': parserinfo.dayfirst = False parserinfo.yearfirst = True else: parserinfo.dayfirst = True parserinfo.yearfirst = False kwargs['dayfirst'] = parserinfo.dayfirst kwargs['yearfirst'] = parserinfo.yearfirst #print('data original', timestr) #print('parserinfo', parserinfo) #print('kwargs', kwargs) data = parser(parserinfo).parse(timestr, **kwargs) #data = parse_datetime_original(timestr, parserinfo, **kwargs) #print('data tratada', data) return data