Exemplo n.º 1
0
def createTransaction(instance, methodType, exchangeCoin, valueInvested, pricePerToken):
    transaction = Transaction()
    transaction.transaction_method = methodType
    transaction.exchange_coin = exchangeCoin
    transaction.user = User.objects.get(username='******')
    transaction.n_tokens = valueInvested
    transaction.price_per_token = pricePerToken
    transaction.fees = 0
    transaction.date = timezone.now()
    transaction.synced_transaction = None
    transaction.save()

    return transaction
Exemplo n.º 2
0
def apiRemCardBonus(request, card_code, salt):
    t_type = Operations.bonus_reduce
    if request.method == 'POST':
        data = request.POST
        if ('key' in data) and ('session_key' in data):
            box = check_license(data['key'], data['session_key'])
            if box:
                try:
                    org = box.co_unit.org
                except:
                    return HttpResponse(status=403)
                    org = None
            else:
                return HttpResponse(status=403)
            if org is not None:
                if org.is_active:
                    try:
                        if 'value' in data:
                            trans = Transaction().create(data)
                            trans.date = datetime.now()

                            card = Card.objects.get(code=card_code, org=org.pk)

                            trans.bonus_before = card.get_total_bonus()

                            # пишем статистику
                            trans.org = org
                            trans.card = card
                            trans.sum = 0
                            trans.bonus_reduce = float(data['value'])
                            trans.type = t_type
                            trans.save()

                            value = float(data['value'])
                            rem_bonus(card, value)

                            return HttpResponse(data['value'])
                        else:
                            return HttpResponse(status='404')
                    except ObjectDoesNotExist as e:
                        return HttpResponse(status='404')
                else:
                    return HttpResponse(status='503')
            else:
                return HttpResponse(status='503')
        else:
            return HttpResponse(status='503')
Exemplo n.º 3
0
def processBtcTransactions(FreezedCurrency):
    r = {
        "processed_addresses": 0,
        "created_transactions": [],
        "errors_transactions": [],
        "errors_addresses": []
    }

    allWallets = Wallet.objects.filter()

    for wallet in allWallets:

        for btcAddress in wallet.getWalletToCcAddresses(currency='BTC'):
            r['processed_addresses'] += 1
            atm = AtmBtc(btcAddress.address.address)
            btcAddress.address.address = atm.clean(btcAddress.address.address)
            try:
                addressRemoteTransactions = atm.getTransactions()
            except Exception, ex:
                addressRemoteTransactions = []
                r['errors_addresses'].append("%s" % (traceback.format_exc()))

            if len(addressRemoteTransactions) > 0:
                for art in addressRemoteTransactions:
                    if art.get("error"):
                        r['errors_addresses'].append(
                            "failed get data for address: %s" %
                            (btcAddress.address.address))
                    else:
                        if art['positive'] and art['confirmations'] > 0:

                            try:
                                new = False
                                try:
                                    transaction = Transaction.objects.get(
                                        hash=art['hash'],
                                        currency="BTC",
                                        address=btcAddress.address)
                                except Transaction.DoesNotExist:
                                    previousCredit = wallet.credit
                                    transaction = Transaction()
                                    transaction.hash = art['hash']
                                    transaction.date = art['date']
                                    transaction.type = 'deposit'
                                    transaction.currency = 'BTC'
                                    transaction.freezedUsd = FreezedCurrency.usd
                                    transaction.freezedEur = FreezedCurrency.eur
                                    transaction.amount = art['value']
                                    transaction.wallet = wallet
                                    transaction.address = btcAddress.address
                                    transaction.save()

                                    # update wallet credit
                                    feePercentage = Configuration(
                                    ).getConfiguration(
                                        "btc_deposit_percentage")
                                    wallet.depositIn(
                                        FreezedCurrency, transaction,
                                        art['value'],
                                        'by AtmBtc found new tx: %s with positive amount: %s (BTC)'
                                        % (art['hash'], art['value']),
                                        feePercentage)
                                    new = True

                                    #all good
                                    # create transactions info btc
                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Currency Rate Date: %s' % strftime(
                                        FreezedCurrency.dateUpdated,
                                        '%Y-%m-%d %H:%M:%S')
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'BTC -> USD'
                                    transactionInfo.cost = FreezedCurrency.usd
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'BTC -> EUR'
                                    transactionInfo.cost = FreezedCurrency.eur
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Previous Credit'
                                    transactionInfo.cost = previousCredit
                                    transactionInfo.save()

                                    transactionInfo = TransactionInfo()
                                    wallet = Wallet.objects.get(id=wallet.id)
                                    transactionInfo.transaction = transaction
                                    transactionInfo.description = 'Current Credit'
                                    transactionInfo.cost = wallet.credit
                                    transactionInfo.save()

                            except Exception, ex:
                                transaction = None

                                r['errors_transactions'].append(
                                    "failed insert for transaction: %s" %
                                    (art['hash']))

                            if new:
                                if transaction:
                                    if not any(x.hash == art['hash'] for x in
                                               r['created_transactions']):
                                        r['created_transactions'].append(
                                            transaction)
                                        # Admin Notification
                                        adminNotification = Notification()
                                        adminNotification.email = True
                                        adminNotification.user = User.objects.get(
                                            username="******")
                                        adminNotification.setEmailData(
                                            "New BTC deposit transaction confirmed",
                                            "notifications/email/admin_email_new_deposit_transaction_confirmed.html",
                                            {
                                                'transaction': transaction,
                                            })
Exemplo n.º 4
0
def rest_add_bonus(request, card_code):
    response = {}

    if request.method == 'PUT':
        user = UserCustom.objects.get(user_id__exact=request.user.pk)
        bonus_data = json.loads(request.body.decode())
        if not user.administrator:
            response['status'] = 'error'
            response['message'] = "Недостаточно прав!"
            return JsonResponse(response, status=503)
        try:
            card = Card.objects.get(org_id__exact=user.org.pk,
                                    code__exact=card_code)
        except:
            response['status'] = 'error'
            response['message'] = "Карта с таким кодом не найдена!"
            return JsonResponse(response, status=400)

        try:
            bonus = Bonus()
            bonus.card = card
            try:
                bonus.active_from = datetime.fromtimestamp(
                    bonus_data['active_from'] / 1000)
            except Exception as exc:
                bonus.active_from = bonus_data['active_from']
            try:
                bonus.active_to = datetime.fromtimestamp(
                    bonus_data['active_to'] / 1000)
            except:
                bonus.active_to = bonus_data['active_to']
            bonus.value = float(bonus_data['value'])
            bonus.enabled = True
            bonus.save()

            trans = Transaction()
            trans.card = card
            trans.type = 'bonus_add'
            trans.date = datetime.now()
            trans.org = user.org
            trans.bonus_add = bonus.value
            trans.workplace = 'ВТИ-ДИСКОНТ'
            trans.doc_close_user = user.user.first_name + " " + user.user.last_name
            trans.save()
        except Exception as err:
            response['status'] = 'error'
            response['message'] = str(err)
            return JsonResponse(response, status=400)

        response['status'] = 'success'
        response['message'] = 'Бонусы добавлены'
        return JsonResponse(response, safe=False)

    if request.method == 'DELETE':
        user = UserCustom.objects.get(user_id__exact=request.user.pk)
        bonus_data = json.loads(request.body.decode())
        try:
            card = Card.objects.get(org_id__exact=user.org.pk,
                                    code__exact=card_code)
        except:
            response['status'] = 'error'
            response['message'] = "Карта с таким кодом не найдена!"
            return JsonResponse(response, status=400)

        try:
            bonus = Bonus.objects.get(id__exact=int(bonus_data['id']))
            bonus.delete()

            trans = Transaction()
            trans.card = card
            trans.type = 'bonus_refund'
            trans.date = datetime.now()
            trans.org = user.org
            trans.bonus_add = bonus.value
            trans.workplace = 'ВТИ-ДИСКОНТ'
            trans.doc_close_user = user.user.first_name + " " + user.user.last_name
            trans.save()
        except Exception as err:
            response['status'] = 'error'
            response['message'] = str(err)
            return JsonResponse(response, status=400)

        response['status'] = 'success'
        response['message'] = 'Бонусы удалены'
        return JsonResponse(response, safe=False)
Exemplo n.º 5
0
                save_question_response(sr, when_question,
                                       line.replace(when_prefix, ''))
            elif line.startswith(improve_prefix):
                save_question_response(sr, improve_question,
                                       line.replace(improve_prefix, ''))
            elif line.startswith(skills_prefix):
                save_question_response(sr, skills_question,
                                       line.replace(skills_prefix, ''))

        save_question_response(sr, t_and_c_question, 'Y')
        save_question_response(sr, bene_question, 'Y')

        if len(row[1]) > 0:
            t = Transaction()
            t.user = user
            t.date = est.localize(dateparser.parse(row[1]))
            t.item = common_item
            t.qty = 1
            t.amount = 3000 if user.email.split(
                '@')[1] == "3cross.coop" else 150
            t.save()
            members_group.user_set.add(user)
        else:
            pending_group.user_set.add(user)

        preferred_shares = 0
        if len(row[21]) > 0:
            preferred_shares = int(row[21])

        if preferred_shares > 0:
            t = Transaction()
Exemplo n.º 6
0
def apiToCardFromService(request):
    if request.method == 'POST':
        data = request.POST
        if ('key' in data) and ('vtikeeper' in data):
            box = CashBox.get_by_key(data['key'])
            if box:
                try:
                    org = box.co_unit.org
                except:
                    org = None
            if org is not None:
                if org.is_active:
                    try:
                        if 'type' in data:
                            if data['type'] == 'add':
                                t_type = Operations.sell
                                if 'value' in data and 'card' in data:
                                    trans = Transaction().create(data)
                                    trans.date = datetime.strptime(
                                        data['datetime'], "%d.%m.%Y %H:%M:%S")
                                    card = Card.objects.get(code=data['card'],
                                                            org=org.pk)

                                    trans.bonus_before = card.get_total_bonus()

                                    d_plan = DiscountPlan.objects.get(
                                        org_id__exact=org.pk)
                                    algorithm = d_plan.algorithm
                                    card.accumulation += float(data['value'])
                                    card.last_transaction_date = datetime.now(
                                    ).date()
                                    card.save()

                                    # пишем статистику
                                    trans.org = org
                                    trans.card = card
                                    trans.sum = float(data['value'])
                                    trans.bonus_reduce = 0
                                    trans.type = t_type

                                    try:
                                        trans.base_doc_date = parse(
                                            data['base_doc_date'])
                                    except:
                                        trans.base_doc_date = None

                                    trans.save()

                                    try:  # Добавляем задание
                                        task = Task(
                                            queue_date=datetime.now(),
                                            execution_date=trans.date +
                                            relativedelta(
                                                days=d_plan.time_delay),
                                            data=data['value'],
                                            card=card,
                                            operation=identify_task_operation(
                                                card, d_plan),
                                            d_plan=d_plan,
                                            transaction=trans,
                                            org=card.org)
                                        task.save()
                                    except:
                                        pass

                                    return HttpResponse(data['value'])
                                else:
                                    return HttpResponse(status='404')
                            if data['type'] == 'rem':
                                t_type = Operations.bonus_reduce
                                if 'value' in data and 'card' in data:
                                    trans = Transaction().create(data)
                                    trans.date = datetime.strptime(
                                        data['datetime'], "%d.%m.%Y %H:%M:%S")
                                    card = Card.objects.get(code=data['card'],
                                                            org=org.pk)

                                    trans.bonus_before = card.get_total_bonus()

                                    # пишем статистику
                                    trans.org = org
                                    trans.card = card
                                    trans.sum = 0
                                    trans.bonus_reduce = float(data['value'])
                                    trans.type = t_type
                                    trans.save()

                                    value = float(data['value'])
                                    rem_bonus(card, value)

                                    return HttpResponse(data['value'])
                                else:
                                    return HttpResponse(status='404')

                    except ObjectDoesNotExist as e:
                        return HttpResponse(status='404')
                else:
                    return HttpResponse(status='503')
            else:
                return HttpResponse(status='503')
        else:
            return HttpResponse(status='503')
Exemplo n.º 7
0
def apiAddAccumToCard(request, card_code, salt):
    t_type = Operations.sell
    if request.method == 'POST':
        data = request.POST
        if ('key' in data) and ('session_key' in data):
            box = check_license(data['key'], data['session_key'])
            if box:
                try:
                    org = box.co_unit.org
                except:
                    return HttpResponse(status=403)
                    org = None
            else:
                return HttpResponse(status=403)
            if org is not None:
                if org.is_active:
                    try:
                        if 'value' in data:
                            value = float(data['value'])
                            trans = Transaction().create(data)
                            trans.date = datetime.now()
                            card = Card.objects.get(code=card_code, org=org.pk)

                            trans.bonus_before = card.get_total_bonus()
                            trans.org = org
                            trans.card = card
                            trans.sum = float(data['value'])
                            trans.bonus_reduce = 0
                            trans.type = t_type
                            try:
                                trans.base_doc_date = parse(
                                    data['base_doc_date'])
                            except:
                                trans.base_doc_date = None

                            d_plan = DiscountPlan.objects.get(
                                org_id__exact=org.pk)

                            algorithm = d_plan.algorithm
                            card.accumulation += float(data['value'])
                            card.last_transaction_date = datetime.now().date()
                            card.save()

                            if value < 0:
                                t_type = Operations.refund
                                trans.type = t_type
                                _handler = __import__(
                                    'core.lib.%s' %
                                    identify_task_operation(card, d_plan),
                                    globals(), locals(), ['count'], 0)
                                card = _handler.count(value, card, d_plan,
                                                      trans)
                                card.save()

                            trans.save()

                            if value > 0:
                                try:  # Добавляем задание
                                    # task = Task(queue_date=datetime.now(),
                                    #             execution_date= datetime.now().date() + relativedelta(days=d_plan.time_delay),
                                    #             data=data['value'],
                                    #             card=card,
                                    #             operation=identify_task_operation(card, d_plan),
                                    #             d_plan=d_plan,
                                    #             transaction=trans,
                                    #             org=card.org)
                                    # task.save()

                                    _handler = __import__(
                                        'core.lib.%s' %
                                        identify_task_operation(card, d_plan),
                                        globals(), locals(), ['count'], 0)
                                    card = _handler.count(
                                        value, card, d_plan, trans)
                                    card.save()

                                except:
                                    pass

                            return HttpResponse(data['value'])
                        else:
                            return HttpResponse(status='404')
                    except ObjectDoesNotExist as e:
                        return HttpResponse(status='404')
                else:
                    return HttpResponse(status='503')
            else:
                return HttpResponse(status='503')
        else:
            return HttpResponse(status='503')