def partner_reward(request): """NOTE: Only Koin endpoint without token auth, as it's not for the app""" partner_uuid = request.GET.get('code') user_email = request.GET.get('email') if partner_uuid and user_email: user = ApiUser.objects.filter(email=user_email).first() partner = KoinPartner.objects.filter(partner_uuid=partner_uuid).first() if user and partner: if user in partner.users_registered.all(): return JsonResponse( {'message': 'Koins already redeemed by the user'}) # Valid redeem user.coins += partner.koin_amount user.partners_registerd.add(partner) user.save() # log transaction admin_user = ApiUser.objects.filter(email=partner.email).first() t = Transaction(amount=coupon.amount, sender=admin_user, receiver=user, created_at=timezone.now(), msg="PARTNER_REDEEM") t.save() return JsonResponse({ 'status': '0', 'message': 'Successfully Redeemed' }) # successfull else: return JsonResponse( {'message': 'User E-mail or Partner Code not valid'}) else: return JsonResponse({'message': 'Parnter'})
def execute_limit_market_transaction(in_order, order, order_type='trade'): order_key = order.s_b + '-' + order.product_code + '-' + str(order.id) print(order_key) # lock the key # [todo] with cache.lock(order_key + "dd"): print(order_key) print(order.dict()) order = cache.get(order_key) # if it's done by others if order is None: return price = min(in_order.price, order.price) amount = min(in_order.remain, order.remain) # update order in_order.remain = in_order.remain - amount order.remain = order.remain - amount if order.remain == 0: cache.delete(order_key) save_completed_order(order.id) else: cache.set(order_key, order, timeout=None) # create transaction transaction = Transaction(**{ 'order1_id': in_order.id, 'order2_id': order.id, 'type': 'trade', 'price': price, 'amount': amount, 'code': order.product_code }) transaction.save() # solve stop order [todo] have problem if order_type == 'trade': order_service.trigger_stop_order(order.product_code, price) # send transaction to trader send_to_trader(in_order.trader_ip, { 'transaction_id': transaction.id, 'type': 'trade', 'order_id': in_order.order_id, 'trade_firm': order.trader_ip, 'number': amount, 'price': price }) send_to_trader(order.trader_ip, { 'transaction_id': transaction.id, 'type': 'trade', 'order_id': order.order_id, 'trade_firm': in_order.trader_ip, 'number': amount, 'price': price })
def create(self, validated_data): user_categories = Category.objects.filter(user=validated_data['user']) transaction = Transaction( description=validated_data['description'], amount=validated_data['amount'], date=validated_data['date'], user=validated_data['user'] ) transaction.save() transaction.categories.set(self.categorize_movement(movement.description, user_categories)) transaction.save() return transaction
def register_user(request): if request.method == "GET": email = request.GET.get('email') name = request.GET.get('name') image = request.GET.get('image') refered_invite_code = request.GET.get('referred_invite_code') if not (email and name): return JsonResponse({'status': '-1'}) # invalid parameters if ApiUser.objects.filter(email=email).exists(): return JsonResponse({'status': '1'}) # Email already exists # create a new user new_user = ApiUser(name=name, email=email, image=image, invite_code=gen_invite_code(name, email)) new_user.token = gen_token(email) refered_by = ApiUser.objects.filter( invite_code=refered_invite_code).first() if refered_by: new_user.refered_invite_code = refered_invite_code new_user.coins = 50 new_user.save() # if refered then referer gets +50 refered_by.coins += 50 refered_by.ref_count += 1 refered_by.save() # log transaction admin_user = ApiUser.objects.filter( email="*****@*****.**").first() t = Transaction(amount=50, sender=admin_user, receiver=refered_by, created_at=timezone.now(), msg="REFERAL") t.save() #TODO: Test it run_promo(refered_by) else: new_user.coins = 50 new_user.save() return JsonResponse({'status': '0'}) # Succesfully registered return JsonResponse({'status': '3'}) # error
def new_transaction(self, status=Transaction.STATUS_PROCESSING, location=Transaction.LOCATION_ORIGIN): """ Create and save a new transaction with the class's item instance. :param status: The Desired status :param location: The Desired location :return: The new instance of Transaction """ trans = Transaction( item=self.item, status=status, location=location ) trans.save() return trans
def run_promo(user): if user.ref_count == 5: config = Config.objects.all().first() curr_time = timezone.now() if config.promo_start_time <= curr_time <= config.promo_end_time: user.coins += config.promo_coin_value admin_user = ApiUser.objects.filter( email="*****@*****.**").first() t = Transaction(amount=config.promo_coin_value, sender=admin_user, receiver=user, created_at=timezone.now(), msg="PROMO") t.save() user.save()
def edittransaction(request, transaction_id): if request.method == 'POST': spending = request.POST['spending'] weekly_expenses = request.POST['weekly_expenses'] item = request.POST['item'] price = request.POST['price'] get_spending = Spending.objects.get(id=spending) get_weekly_expenses = WeeklyExpenses.objects.get(id=weekly_expenses) updated_date = timezone.now() update_transaction = Transaction.objects.get( id=transaction_id) update_transaction.item = item update_transaction.price = price update_transaction.spending = get_spending update_transaction.weekly_expenses = get_weekly_expenses update_transaction.updated_date = updated_date update_transaction.save() return redirect('backoffice-list-transaction') else: list_spending = Spending.get_spending_list() list_weekly_expenses = WeeklyExpenses.get_list_weekly_expenses() list_transaction = Transaction.get_detail_transaction( transaction_id) return render(request, 'backoffice/edit-transaction.html', {'list_transaction': list_transaction, 'transaction_id': transaction_id, 'list_spending': list_spending, 'list_weekly_expenses': list_weekly_expenses})
def execute_cancel_transaction(order): stop_cache = caches['stop'] left_orders = [] stop_keys = stop_cache.keys('*') is_stop = False for stop_key in stop_keys: stop_order = stop_cache.get(stop_key) if stop_order.order_id == order.order_id: left_orders.append(stop_order) stop_cache.delete(stop_key) save_canceled_order(stop_order.id) is_stop = True if not is_stop: market_depth = market_depth_service.get_market_depth(order.s_b, order.product_code) for item in market_depth: if item.order_id == order.order_id: cache.delete(item.s_b + '-' + item.product_code + '-' + str(item.id)) save_canceled_order(item.id) left_orders.append(item) for left_order in left_orders: # save transaction transaction = Transaction(**{ 'order1_id': order.id, 'order2_id': 0, 'type': 'cancel', 'price': 0, 'amount': left_order.remain, 'code': left_order.product_code }) transaction.save() # send transaction to trader send_to_trader(order.trader_ip, { 'transaction_id': transaction.id, 'order_id': order.order_id, 'type': 'cancel', 'number': left_order.remain, 'trade_firm': '', 'price': 0 })
def move(self, request, *args, **kwargs): """ Given the primary key of the item, we query the latest transaction, than create a new transaction based on it's next state. Note: by saving the transaction, the item state will be updated as well. :param request: The Request object :param args: Arguments :param kwargs: Key word arguments :return: Response """ trans = Transaction.get_active_transaction(kwargs['id']) return self.move_transaction(trans)
def insert_to_db(data): card = Card.objects.get(no=data['card']) terminal = Terminal.objects.get(id=data['terminal']) arqc = ARQC.objects.get(id=data['arqc']) merchant = Merchant.objects.get(id=data['merchant']) transaction = Transaction(type=data['type'], date=data['date'], batch_no=data['batch_no'], ref_no=data['ref_no'], base=data['base'], tips=data['tips'], arqc=arqc, card=card, terminal=terminal, merchant=merchant, trace_no=data['trace_no'], app_code=data['app_code']) transaction.save() print(type(transaction.type))
def pay(self, transaction_data): transaction_serializer = TransactionSerializer(data=transaction_data) if not transaction_serializer.is_valid(): raise Exception('invalid transaction data') transaction = Transaction(**transaction_serializer.validated_data) if transaction.type == 'authorisation': return self._authorize(transaction) elif transaction.type == 'presentment': return self._execute_presentment(transaction) else: raise Exception(transaction.type + " transaction type was not implemented yet!")
def addtransactionindex(request, spending_id): if request.method == 'POST': active_schedule = Period.objects.filter(completed=False).first() item = request.POST['item'] price = request.POST['price'] weekly_expenses = request.POST['weekly_expenses'] get_spending = Spending.objects.get(id=spending_id) get_weekly_expenses = WeeklyExpenses.objects.get(id=weekly_expenses) created_date = timezone.now() updated_date = timezone.now() add_transaction = Transaction(item=item, price=price, spending=get_spending, weekly_expenses=get_weekly_expenses, period=active_schedule, created_date=created_date, updated_date=updated_date) add_transaction.save() return redirect('index') else: list_spending = Spending.get_detail_spending(spending_id) list_weekly_expenses = WeeklyExpenses.get_weekly_expenses_list_by_spending( spending_id) return render(request, 'backoffice/add-transaction-index.html', { 'list_weekly_expenses': list_weekly_expenses, 'list_spending': list_spending, 'spending_id': spending_id, })
def transfer_coin(request): if request.method == "GET": token = request.GET.get('token') rcv_email = request.GET.get('email') amount = int(request.GET.get('amount', 0)) if token and (rcv_email and amount): sender = ApiUser.objects.filter(token=token).first() receiver = ApiUser.objects.filter(email=rcv_email).first() if not sender: return JsonResponse({'status': '1'}) # No sender if not receiver: return JsonResponse({'status': '2'}) # No receiver if sender.coins < amount: return JsonResponse({'status': '3'}) # Insufficient balance if amount <= 0: return JsonResponse({'status': '4'}) # Not valid amount if sender == receiver: return JsonResponse({'status': '5'}) # Not valid # Valid data sender.coins -= amount receiver.coins += amount sender.save() receiver.save() # log transaction t = Transaction(amount=amount, sender=sender, receiver=receiver, created_at=timezone.now(), msg="USER_TRANSFER") t.save() return JsonResponse({'status': '0'}) # valid return JsonResponse({'status': '-1'}) # Error
def transfer_eurekoin(request): email = request.GET.get('email', "") amount = int(request.GET.get('amount', 25)) if email and amount: receiver = ApiUser.objects.filter(email=email).first() if receiver: receiver.coins += amount # log transaction admin_user = ApiUser.objects.filter( email="*****@*****.**").first() t = Transaction(amount=amount, sender=admin_user, receiver=receiver, created_at=timezone.now(), msg="ADMIN_TRANSFER") t.save() receiver.save() return HttpResponseRedirect('/api/transfer_admin/', {})
def redeem_coupon(request): token = request.GET.get('token') code = request.GET.get('code') if token and code: user = ApiUser.objects.filter(token=token).first() if user: coupon = Coupon.objects.filter(code=code).first() if coupon: if not coupon.is_active: return JsonResponse({'status': '4'}) # Coupon expired # TODO: Unoptimized code! use DB functions if user in coupon.users.all(): return JsonResponse({'status': '3'}) # Coupon already used by user # Valid redeem user.coins += coupon.amount user.coupons_used.add(coupon) coupon.use_count += 1 coupon.save() user.save() # log transaction admin_user = ApiUser.objects.filter( email="*****@*****.**").first() t = Transaction(amount=coupon.amount, sender=admin_user, receiver=user, created_at=timezone.now(), msg="COUPON_REDEEM") t.save() return JsonResponse({'status': '0'}) # successfull else: return JsonResponse({'status': '2'}) # No such coupon else: return JsonResponse({'status': '1'}) # No such user
def transaction_create(request): """マーチング実施""" transaction = Transaction(); if request.method == 'POST': form = TransactionForm(request.POST, request.FILES, instance=transaction); if form.is_valid(): transaction = form.save() if transaction.type == '1' : # 特徴量マッチング処理 try: status = handler_surf(transaction,request) transaction.dest_image = os.path.join("transaction", "result", os.path.basename(transaction.src_image.path)) transaction.save() if status: messages.info(request, '特徴量マッチング処理が正常に終了しました。') except: messages.error(request, '特徴量マッチング処理が失敗しました。') return render(request, 'transaction/create.html', dict(form=form)) else: # テンプレートマッチング処理 try: status = handler(transaction,request) transaction.dest_image = os.path.join("transaction", "result", os.path.basename(transaction.src_image.path)) transaction.save() if status: messages.info(request, 'テンプレートマッチング処理が正常に終了しました。') except: messages.error(request, 'テンプレートマッチング処理が失敗しました。') return render(request, 'transaction/create.html', dict(form=form)) return redirect('template:transaction_list') else: form = TransactionForm(instance=transaction) return render(request, 'transaction/create.html', dict(form=form))
def add_money(amount, save=False, date=None): """ For adding/subtracting money to all budgets based on their percentage attribute. To add money to a single budget use the admin inferface... for now. Example: if food gets 30% of the budget, and you were to call this function with amount=100, then this would create a transaction on the food budget for 30$ :param amount: amount in dollars you wish to add between all budgets. If the number is negative, this will subtract from all budgets the same way. :raises ValueError: if budgets are not balanced :returns list of transactions: """ # ensuring budgets are balanced assert budgets_sum_to_one() is None # defaults to today date = datetime.date.today() if date is None else date added_transactions = [] for budget in Budget.objects.all(): trans_amount = amount * budget.percentage transaction = Transaction( amount=trans_amount, budget=budget, description="add_money: Total amount added %.2f" % float(amount), date=date, ) if save: transaction.save() added_transactions.append(transaction) return added_transactions
def move_transaction(self, trans: Transaction) -> Response: """ Gets the next transaction in the state chain, and saves it. Returns an error response object if not in the correct status or locations (see status chart) :param trans: Transaction :return: Response """ next_trans = trans.get_next_transaction_from_state() if next_trans: return Response(self.get_serializer(next_trans.item).data) else: return Response(data={ "status": "error", "details": "Transactions already in finished state" }, status=status.HTTP_400_BAD_REQUEST)
def refund(self, request, obj): """ Refund a payment that is in error :param request: The request :param obj: The Item in question :return: None """ trans = Transaction.get_active_transaction(obj.id) if trans.status != Transaction.STATUS_ERROR: self.message_user( request, "The active transaction for item {} is not in an error state and cannot be refunded" .format(obj.id), level=messages.ERROR) else: obj.refund()
def error(self, request, *args, **kwargs): """ Create an error transaction if the latest transaction is being processed and it's location is 'routable' :param request: The Request object :param args: Arguments :param kwargs: Key word arguments :return: Response """ trans = Transaction.get_active_transaction(kwargs['id']) if trans.status != Transaction.STATUS_PROCESSING or trans.location != Transaction.LOCATION_ROUTABLE: return Response(data={ "status": "error", "details": "Transactions not in correct state: [{}, {}]".format( trans.status, trans.location) }, status=status.HTTP_400_BAD_REQUEST) trans.item.error() return Response(self.get_serializer(trans.item).data)
def liststransaction(request): active_schedule = Period.objects.filter(completed=False).first() list_transaction = Transaction.get_list_transaction(active_schedule) return render(request, 'backoffice/backoffice-transaction.html', {'list_transaction': list_transaction})
def transactionperiod(request): list_spending = Spending.get_spending_list() current_date = timezone.now() desc_current_date_third = arrow.get(current_date).to(TIME_ZONE) desc_current_date = desc_current_date_third.strftime("%Y-%m-%d") desc_current_date_second = desc_current_date_third.strftime("%d-%b-%Y") current_month = str(desc_current_date_third.strftime('%m')) current_year = str(desc_current_date_third.strftime('%Y')) filter_start_date_of_month = "%s-%s-01" % (current_year, current_month) filter_start_date_of_month_second = datetime.datetime.strptime( filter_start_date_of_month, '%Y-%m-%d') filter_end_date_of_month = last_day_of_month( filter_start_date_of_month_second) filter_end_date_of_month = filter_end_date_of_month.strftime("%Y-%m-%d") dt = datetime.datetime.strptime(desc_current_date, '%Y-%m-%d') dt_last = dt+datetime.timedelta(hours=23, minutes=59, seconds=59) filter_dt = dt.strftime('%Y-%m-%d') filter_dt_last = dt_last.strftime('%Y-%m-%d') start = dt - datetime.timedelta(days=dt.weekday()) end = start + datetime.timedelta(days=7) end_second = start + datetime.timedelta(days=6) today_plus_one_day = dt + datetime.timedelta(days=1) filter_current_date_plus_one_day = today_plus_one_day.strftime('%Y-%m-%d') filter_start_date_of_week = start.strftime('%Y-%m-%d') filter_end_date_of_week = end.strftime('%Y-%m-%d') if 'filter_data_transaction' in request.GET: if request.GET['filter_data_transaction']: filter_data_transaction = request.GET['filter_data_transaction'] else: filter_data_transaction = '1' else: filter_data_transaction = '1' if 'filter_spending' in request.GET: if request.GET['filter_spending']: filter_spending = request.GET['filter_spending'] else: filter_spending = '' else: filter_spending = '' if 'filter_start_date' in request.GET: if request.GET['filter_start_date']: filter_start_date_second = request.GET['filter_start_date'] filter_start_date = datetime.datetime.strptime( filter_start_date_second, "%d-%b-%Y").strftime('%Y-%m-%d') else: filter_start_date_second = '' filter_start_date = '' else: filter_start_date_second = '' filter_start_date = '' if 'filter_end_date' in request.GET: if request.GET['filter_end_date']: filter_end_date_second = request.GET['filter_end_date'] filter_end_date = datetime.datetime.strptime( request.GET['filter_end_date'], "%d-%b-%Y").strftime('%Y-%m-%d') else: filter_end_date_second = '' filter_end_date = '' else: filter_end_date_second = '' filter_end_date = '' if filter_data_transaction == '1': list_transaction = Transaction.get_list_transaction_period( filter_dt, filter_current_date_plus_one_day, filter_spending) desc_list_transaction = "Today" elif filter_data_transaction == '2': list_transaction = Transaction.get_list_transaction_period( filter_start_date_of_week, filter_end_date_of_week, filter_spending) desc_list_transaction = "Week" elif filter_data_transaction == '3': list_transaction = Transaction.get_list_transaction_period( filter_start_date_of_month_second, filter_end_date_of_month, filter_spending) desc_list_transaction = "Month" elif filter_data_transaction == '4': list_transaction = Transaction.get_list_transaction_period( filter_start_date, filter_end_date, filter_spending) desc_list_transaction = "Custom" return render(request, 'backoffice/backoffice-transaction-period.html', {'list_transaction': list_transaction, 'desc_list_transaction': desc_list_transaction, 'filter_data_transaction': filter_data_transaction, 'list_spending': list_spending, 'filter_spending': filter_spending, 'filter_start_date': filter_start_date_second, 'filter_end_date': filter_end_date_second, })
def charttransaction(request): list_spending = Spending.get_spending_list() list_weekly_expenses = WeeklyExpenses.get_weekly_expenses_list() current_date = timezone.now() desc_current_date_third = arrow.get(current_date).to(TIME_ZONE) desc_current_date = desc_current_date_third.strftime("%Y-%m-%d") desc_current_date_second = desc_current_date_third.strftime("%d-%b-%Y") current_month = str(desc_current_date_third.strftime('%m')) current_year = str(desc_current_date_third.strftime('%Y')) filter_start_date_of_month = "%s-%s-01" % (current_year, current_month) filter_start_date_of_month_second = datetime.datetime.strptime( filter_start_date_of_month, '%Y-%m-%d') filter_end_date_of_month = last_day_of_month( filter_start_date_of_month_second) filter_end_date_of_month = filter_end_date_of_month.strftime("%Y-%m-%d") dt = datetime.datetime.strptime(desc_current_date, '%Y-%m-%d') dt_last = dt+datetime.timedelta(hours=23, minutes=59, seconds=59) filter_dt = dt.strftime('%Y-%m-%d') filter_dt_last = dt_last.strftime('%Y-%m-%d') start = dt - datetime.timedelta(days=dt.weekday()) end = start + datetime.timedelta(days=7) end_second = start + datetime.timedelta(days=6) today_plus_one_day = dt + datetime.timedelta(days=1) filter_current_date_plus_one_day = today_plus_one_day.strftime('%Y-%m-%d') filter_start_date_of_week = start.strftime('%Y-%m-%d') filter_end_date_of_week = end.strftime('%Y-%m-%d') filter_end_date_of_week_minus_one_day = end_second.strftime('%Y-%m-%d') if 'filter_start_date' in request.GET: if request.GET['filter_start_date']: filter_start_date_second = request.GET['filter_start_date'] filter_start_date = datetime.strptime( filter_start_date_second, "%d-%b-%Y").strftime('%Y-%m-%d') else: filter_start_date_second = '' filter_start_date = '' else: filter_start_date_second = '' filter_start_date = '' if 'filter_end_date' in request.GET: if request.GET['filter_end_date']: filter_end_date_second = request.GET['filter_end_date'] filter_end_date = datetime.strptime( request.GET['filter_end_date'], "%d-%b-%Y").strftime('%Y-%m-%d') else: filter_end_date_second = '' filter_end_date = '' else: filter_end_date_second = '' filter_end_date = '' if 'filter_data_transaction' in request.GET: if request.GET['filter_data_transaction']: filter_data_transaction = request.GET['filter_data_transaction'] else: filter_data_transaction = '1' else: filter_data_transaction = '1' if 'filter_spending' in request.GET: if request.GET['filter_spending']: filter_spending = request.GET['filter_spending'] else: filter_spending = '' else: filter_spending = '' if 'filter_weekly_expenses' in request.GET: if request.GET['filter_weekly_expenses']: filter_weekly_expenses = request.GET['filter_weekly_expenses'] else: filter_weekly_expenses = '' else: filter_weekly_expenses = '' list_transaction_period_today = {'label': [], 'dataset': []} list_transaction_period_week = {'label': [], 'dataset': []} list_transaction_period_month = {'label': [], 'dataset': []} list_chart_spending_today = {'chart': [], 'label': [], 'dataset': ''} list_chart_spending_week = {'chart': [], 'label': [], 'dataset': ''} list_chart_spending_month = {'chart': [], 'label': [], 'dataset': ''} if filter_data_transaction == '1': list_chart_spending_today = Transaction.get_total_transaction_per_spending( filter_dt, filter_current_date_plus_one_day) list_transaction_period_today = Transaction.get_total_transaction_per_period_id( filter_start_date_of_week, filter_end_date_of_week_minus_one_day, filter_spending) # total_transaction_period = Spending.get_total_transaction_per_period( # filter_dt, filter_dt_last, filter_spending, filter_weekly_expenses) # print(list_transaction_period_today) desc_list_transaction = "Today" elif filter_data_transaction == '2': list_chart_spending_week = Transaction.get_total_transaction_per_spending( filter_start_date_of_week, filter_end_date_of_week_minus_one_day) list_transaction_period_week = Transaction.get_total_transaction_per_period_id( filter_start_date_of_week, filter_end_date_of_week_minus_one_day, filter_spending) # print(list_transaction_period_week) # print(list_transaction_period_week) # total_transaction_period = Spending.get_total_transaction_per_period_id( # filter_start_date_of_week, filter_end_date_of_week_minus_one_day, filter_spending, filter_weekly_expenses) desc_list_transaction = "Week" elif filter_data_transaction == '3': list_transaction_period_month = Transaction.get_total_transaction_per_period_id( filter_start_date_of_month, filter_end_date_of_month, filter_spending) list_chart_spending_month = Transaction.get_total_transaction_per_spending( filter_start_date_of_month, filter_end_date_of_month) # total_transaction_period = Spending.get_total_transaction_per_period_id( # filter_start_date_of_month, filter_end_date_of_month, filter_spending, filter_weekly_expenses) desc_list_transaction = "Mounth" # elif filter_data_transaction == '4': # if filter_start_date and filter_end_date: # total_transaction_period = Spending.get_total_transaction_per_period_id( # filter_start_date, filter_end_date, filter_spending, filter_weekly_expenses) # desc_list_transaction = "Custom" return render(request, 'backoffice/chart-transaction.html', {'list_weekly_expenses': list_weekly_expenses, 'list_spending': list_spending, 'filter_start_date': filter_start_date, 'filter_end_date': filter_end_date, 'filter_data_transaction': filter_data_transaction, 'filter_spending': filter_spending, 'filter_weekly_expenses': filter_weekly_expenses, # 'transaction_per_spending': transaction_per_spending, 'list_chart_spending_today': list_chart_spending_today, 'list_chart_spending_week': list_chart_spending_week, 'list_chart_spending_month': list_chart_spending_month, 'list_transaction_period_today': list_transaction_period_today, 'list_transaction_period_week': list_transaction_period_week, 'list_transaction_period_month': list_transaction_period_month, # 'total_transaction_period': total_transaction_period, # 'desc_list_transaction': desc_list_transaction })
def new_site(self, data): tx = Transaction.create_and_send_mail(data) LOG.info('Create new site %s', tx)