Exemplo n.º 1
0
    def put(self, request):
        """Receive a rows from data table and add to existing google sheet & add to DB"""

        body_unicode = request.body.decode('utf-8')
        data = json.loads(body_unicode)
        user_id = settings.DEFAULT_USER
        if isinstance(data['tableRows'], list):
            spread_sheet = gc.open(data['title'])
            wks = spread_sheet[0]
            for row in data['tableRows']:
                data_dict = dict(zip(data['tableKeys'], row))
                data_dict.update({'user_id': user_id})
                exists_db = Transaction.objects.filter(
                    date=data_dict.get('date'),
                    amount=data_dict.get('amount'),
                    location=data_dict.get('location'),
                    user_id=user_id

                )
                if not exists_db:
                    wks.append_table(values=row)
                    transaction = Transaction(**data_dict)
                    transaction.save()
            return JsonResponse({'success': 'true'}, status=200)
        return JsonResponse({'success': 'false'}, status=400)
Exemplo n.º 2
0
def parse_transaction(byte_stream):
    byte_stream = streamify_if_bytes(byte_stream)

    version_bytes = byte_stream.read(4)
    version = int.from_bytes(version_bytes, "little")

    num_inputs = decode_varint(byte_stream)
    # a 0x00 here is the Segwit marker
    is_segwit = num_inputs == 0
    if is_segwit:
        # next byte is flag
        _ = byte_stream.read(1)[0]  # should be nonzero (0x01 currently)
        num_inputs = decode_varint(byte_stream)

    inputs = [parse_input(byte_stream) for _ in range(num_inputs)]

    num_outputs = decode_varint(byte_stream)
    outputs = [parse_output(byte_stream, n) for n in range(num_outputs)]

    if is_segwit:
        witnesses = [parse_witness(byte_stream) for _ in range(num_inputs)]
        for input_, witness in zip(inputs, witnesses):
            input_.witness = witness

    locktime_bytes = byte_stream.read(4)
    locktime = int.from_bytes(locktime_bytes, "little")

    transaction = Transaction(version=version, locktime=locktime)

    return transaction, inputs, outputs
Exemplo n.º 3
0
def create_transaction(request):
    user_id = request.user.id
    try:
        account = Account.objects.get(pk=request.POST['account_id'],
                                      user_id=user_id)
        envelope = Envelope.objects.get(pk=request.POST['envelope_id'],
                                        user_id=user_id)
    except:
        raise Http404('Not found')

    amount = float(request.POST['amount'])
    if 'subtract' in request.POST:
        amount = amount * -1.00

    try:
        transaction = Transaction(account=account,
                                  envelope=envelope,
                                  date=request.POST['date'],
                                  amount=amount)
    except (KeyError):
        messages.add_message(request, messages.ERROR,
                             'Something squiffy happened.')
        return render(request, 'envelopes/index.html')
    else:
        transaction.save()
        messages.add_message(request, messages.SUCCESS, 'Transaction added.')
        return HttpResponseRedirect(
            reverse('envelopes:detail', args=(envelope.id, )))
Exemplo n.º 4
0
def calculate_interest():
    accounts = BorrowerBankAccount.objects.filter(
        balance__gt=0,
        interest_start_date__gte=timezone.now(),
        initial_deposit_date__isnull=False).select_related('account_type')

    this_month = timezone.now().month

    created_transactions = []
    updated_accounts = []

    for account in accounts:
        if this_month in account.get_interest_calculation_months():
            interest = account.account_type.calculate_interest(account.balance)
            account.balance += interest
            account.save()

            transaction_obj = Transaction(account=account,
                                          transaction_type=INTEREST,
                                          amount=interest)
            created_transactions.append(transaction_obj)
            updated_accounts.append(account)

    if created_transactions:
        Transaction.objects.bulk_create(created_transactions)

    if updated_accounts:
        BorrowerBankAccount.objects.bulk_update(updated_accounts, ['balance'])
Exemplo n.º 5
0
    def create(self, validated_data):
        """Custom `create()` method to set the `created_by` value."""
        _data = self._handle_related_fields(validated_data)
        instance = Transaction(**_data)
        instance.created_by = self.context['request'].user
        instance.updated_by = self.context['request'].user
        instance.save()

        return instance
Exemplo n.º 6
0
    def __init__(self):
        self.transaction = Transaction()

        self.transaction.date = self.__random_date__()
        self.transaction.description = self.__random_string__()
        self.transaction.amount = self.__random_decimal__()
        self.transaction.current_balance = self.__random_decimal__()
        self.transaction.date_imported = self.__random_date__()
        self.transaction.custom_date_1 = self.__random_date__()
        self.transaction.custom_text_1 = self.__random_string__()
Exemplo n.º 7
0
def cancel(request):
    try:
        selected_session = Session.objects.get(pk=request.POST['choice'])
    except (KeyError, Session.DoesNotExist):
        # Redisplay the session voting form.
        return render(request, 'session_list.html', {
            'error_message': "You didn't select a session.",
        })
    else:
        if (selected_session.start_time - timezone.now() <=
                datetime.timedelta(hours=24)):
            return render(request, 'session_list.html', {
                'error_message':
                "Cannot cancel sessions in coming 24 hours.",
            })
        else:
            student = Student.objects.get(student=request.user)
            amount = selected_session.tutor.hourlyRate * 1.05
            w = Wallet.objects.get(owner=student.student)
            w.balance += Decimal(amount)
            new_trans = Transaction(owner=request.user,
                                    amount=amount,
                                    timestamp=timezone.now())
            endtime = str(selected_session.end_time)
            body = 'Dear ' + selected_session.tutor.tutor.get_full_name(
            ) + ',\n' + 'A session booked by ' + selected_session.student.student.get_full_name(
            ) + ' from ' + str(selected_session.start_time) + ' to ' + str(
                selected_session.end_time
            ) + ' is cancelled. Go to Tutoria Homepage to check it out.\nTutoria'
            mail.send_mail('A session is cancelled', body, '*****@*****.**',
                           [selected_session.tutor.tutor.email])

            body = 'Dear ' + selected_session.student.student.get_full_name(
            ) + ',\n' + 'A session taught by ' + selected_session.tutor.tutor.get_full_name(
            ) + ' from ' + str(selected_session.start_time) + ' to ' + str(
                selected_session.end_time
            ) + ' is cancelled. Your wallet value now is: $' + str(
                w.balance
            ) + '. Go to Tutoria Homepage to check it out.\nTutoria'
            mail.send_mail('A session is cancelled', body, '*****@*****.**',
                           [selected_session.student.student.email])

            unavail = NotAvailableSlot.objects.get(
                tutor=selected_session.tutor,
                start_time=selected_session.start_time,
                end_time=selected_session.end_time)
            unavail.delete()
            selected_session.delete()
            new_trans.save()
            student.save()
            w.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return render(request, 'cancelok.html')
Exemplo n.º 8
0
 def create_transactions(self, user):
     from decimal import Decimal
     from os import urandom
     import binascii
     from random import randrange
     user_transactions = [
         Transaction(value=Decimal(randrange(10, 100000)) / 100,
                     type_transaction=int(randrange(0, 2)),
                     name=binascii.hexlify(urandom(16)),
                     wallet=user.wallet) for i in range(30)
     ]
     Transaction.objects.bulk_create(user_transactions)
Exemplo n.º 9
0
def create_transaction(document_uploaded, transaction_date, debit, credit,
                       balance):
    transaction = Transaction(transaction_doc=document_uploaded)
    print transaction
    print "saving now...."
    transaction.transaction_date = transaction_date
    transaction.debit = debit
    transaction.credit = credit
    transaction.balance = balance

    print transaction
    transaction.save()
Exemplo n.º 10
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.º 11
0
 def save_transaction(self, serializer):
     t = Transaction()
     t.origin = serializer.validated_data["origin"]
     t.destination = serializer.validated_data["destination"]
     t.ammount = serializer.validated_data["ammount"]
     t.coin_type = serializer.validated_data["coin_type"]
     if t.origin.balance - t.ammount < 0:
         raise Exception("El origen no tenia fondos")
     t.origin.balance = t.origin.balance - t.ammount
     t.destination.balance = t.destination.balance + t.ammount
     t.origin.save()
     t.destination.save()
     serializer.save()
Exemplo n.º 12
0
    def refill(cls, date, account, envelopes, amount, immutable=None):
        if len(envelopes) < 1:
            raise ValueError('No envelopes to be filled.')

        ratio = 1.0
        total = 0.0

        for envelope in envelopes:
            total += float(envelope.monthly_budget)

        if total > amount:
            if immutable:
                raise ValueError(
                    'Not enough funds to refill the given envelopes.')
            else:
                ratio = amount / total

        transactions = 0
        for envelope in envelopes:
            transaction_amount = round(
                float(envelope.monthly_budget) * ratio, 2)
            if transaction_amount > 0.0:
                amount -= transaction_amount
                transaction = Transaction(account=account,
                                          envelope=envelope,
                                          date=date,
                                          amount=transaction_amount)
                transaction.save()
                transactions += 1

        if amount > 0.0:
            transaction = Transaction(account=account,
                                      date=date,
                                      amount=round(amount, 2))
            transaction.save()
            transactions += 1

        return transactions
Exemplo n.º 13
0
    def post(self, **kwargs):
        tx = Transaction()
        data = kwargs.get('data')
        userP = UserProfile.objects.get(
            user_external_reference=data['user_id'])
        data['user_id'] = userP.user
        field_names = [
            name for name in tx._meta.get_all_field_names() if name in data
        ]

        for name in field_names:
            setattr(tx, name, data[name])
        tx.save()

        return tx
Exemplo n.º 14
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.º 15
0
    def post(self, request, format=None):
        serializer = UserSerializer(data=request.data)

        if serializer.is_valid():
            user = User.objects.create_user(
                serializer.data['email'],
                request.data['password'],
                firstname=serializer.data['firstname'],
                lastname=serializer.data['lastname'],
                is_children=False
            )

            token = Token.objects.get(user=user)

            # Create a Family instance
            family = Family(user=user)
            family.save()

            # Create a FamilyMember
            familyMember = FamilyMember(user=user, family=family)
            familyMember.save()

            # Set balance of the current account to 1000 and an initial transaction
            account = Account.objects.filter(user=user).first()
            newBalance = 1000

            transaction = Transaction(
                account_to=account,
                account_from=account,
                amount=newBalance,
                date_validated=datetime.now()
            )
            transaction.save()

            Account.objects.filter(user=user).update(balance=newBalance)

            return Response({
                'status': status.HTTP_200_OK,
                'token': token.key,
            })
        else:
            return Response({
                "status": status.HTTP_404_NOT_FOUND,
                'message': serializer.errors,
            }, status=status.HTTP_404_NOT_FOUND)
Exemplo n.º 16
0
    def form_valid(self, form):
        account_name = form.cleaned_data['account_name']
        initial_balance = form.cleaned_data['initial_balance']
        date = form.cleaned_data['date']
        account_type = form.cleaned_data['account_type']
        balance_description = 'initial'
        form.instance.user = self.request.user
        self.object = form.save()
        account_record = Account.objects.filter(account_name=account_name,
                                                user=self.request.user.id)
        print('account record:')
        print(account_record)
        category = Category.objects.filter(category='Initial Balance',
                                           user=self.request.user.id)
        print(category)
        new_record = AccountBalance(account=account_record[0],
                                    balance_description=balance_description,
                                    balance=initial_balance,
                                    balance_date=date.date())
        new_record.save()

        initial_balance_transaction = Transaction(
            user=self.request.user,
            store=account_name,
            description=balance_description,
            amount=initial_balance,
            trans_date=date.date(),
            category=category[0],
            account_name=account_record[0])
        initial_balance_transaction.save()
        new_record_history = AccountHistory(
            user=self.request.user,
            account=account_record[0],
            transaction=initial_balance_transaction,
            date=date,
            balance=initial_balance)
        new_record_history.save()
        total_budget_left = 0

        print(initial_balance_transaction)
        return super().form_valid(form)
Exemplo n.º 17
0
def create_transaction(request):
    account = get_object_or_404(Account, pk=request.POST['account_id'])
    envelope = get_object_or_404(Envelope, pk=request.POST['envelope_id'])
    amount = request.POST['amount']
    if 'subtract' in request.POST:
        amount = float(amount) * -1.00

    try:
        transaction = Transaction(account=account,
                                  envelope=envelope,
                                  date=request.POST['date'],
                                  amount=amount)
    except (KeyError):
        messages.add_message(request, messages.ERROR,
                             'Something squiffy happened.')
        return render(request, 'accounts/index.html')
    else:
        transaction.save()
        messages.add_message(request, messages.SUCCESS, 'Transaction added.')
        return HttpResponseRedirect(
            reverse('accounts:detail', args=(account.id, )))
Exemplo n.º 18
0
 def prepare_transaction(self, transactions: list):
     for transaction_data in transactions:
         transaction_data["user_id"] = self.user_id
         yield Transaction(**transaction_data)
Exemplo n.º 19
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.º 20
0
    def form_valid(self, form):
        ok = True

        the_student = Student.objects.get(student=self.request.user)
        the_tutor = Tutor.objects.get(pk=self.kwargs['tutor_id'])
        notAvailable = NotAvailableSlot.objects.filter(tutor=the_tutor)
        st = form.instance.start_time
        et = st + datetime.timedelta(minutes=the_tutor.timePerSlot)

        for slot in notAvailable:
            if (slot.start_time <= st) and (slot.end_time >= et):
                ok = False
                messages.error(self.request,
                               'Crashed with Tutor Unavailable Slots.')

        if ok:
            mylist = Session.objects.filter(student=the_student)
            for booking in mylist:
                if (booking.start_time.date() == st.date()) and (booking.tutor
                                                                 == the_tutor):
                    ok = False
                    messages.error(
                        self.request,
                        'Cannot book more than one slot of same tutor in a day.'
                    )

            if (st - timezone.now() <= datetime.timedelta(hours=24)):
                ok = False
                messages.error(self.request,
                               'Cannot book session within coming 24 hours.')

            if (st - timezone.now() > datetime.timedelta(days=7)):
                ok = False
                messages.error(self.request,
                               'Cannot book further than 7 days.')

            if (Wallet.objects.get(owner=the_student.student).balance <
                (the_tutor.hourlyRate) * 1.05):
                ok = False
                messages.error(self.request, 'You do not have enough money.')

            if (st.time() < datetime.time(hour=9)) or (et.time() >
                                                       datetime.time(hour=22)):
                ok = False
                messages.error(
                    self.request,
                    'Exceeded allowable time range. 9am-10pm only.')

        if ok:
            form.instance.student = the_student
            form.instance.tutor = the_tutor
            form.instance.end_time = et
            w = Wallet.objects.get(owner=the_student.student)
            new_unavail = NotAvailableSlot(tutor=the_tutor,
                                           start_time=st,
                                           end_time=et)
            w.balance = w.balance - Decimal((the_tutor.hourlyRate) * 1.05)
            new_trans = Transaction(owner=self.request.user,
                                    amount=(-(the_tutor.hourlyRate) * 1.05),
                                    timestamp=timezone.now())

            body = 'Dear ' + the_tutor.tutor.get_full_name(
            ) + ',\n' + 'A session is booked by ' + the_student.student.get_full_name(
            ) + ' from ' + str(st) + ' to ' + str(
                et) + '. Go to Tutoria Homepage to check it out.\nTutoria'
            mail.send_mail('A session is booked', body, '*****@*****.**',
                           [the_tutor.tutor.email])

            body = 'Dear ' + the_student.student.get_full_name(
            ) + ',\n' + 'A session taught by ' + the_tutor.tutor.get_full_name(
            ) + ' from ' + str(st) + ' to ' + str(
                et) + ' is booked. Your wallet value now is: $' + str(
                    w.balance
                ) + '. Go to Tutoria Homepage to check it out.\nTutoria'
            mail.send_mail('A session is cancelled', body, '*****@*****.**',
                           [the_student.student.email])

            new_trans.save()
            new_unavail.save()
            the_student.save()
            w.save()
            return super(MakeBooking, self).form_valid(form)
        else:
            return super(MakeBooking, self).form_invalid(form)
Exemplo n.º 21
0
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "discountServer.settings")
    try:
        import django
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        raise

    django.setup()

    from queues.models import Task
    from cards.models import Card
    from core.models import DiscountPlan
    from transactions.models import Transaction
    from datetime import datetime

    cards = Card.objects.filter(org_id__exact=3)
    d_plan = DiscountPlan.objects.get(org_id__exact=3)
    for card in cards:
        print(card.code)

        _handler = __import__('core.lib.%s' % d_plan.algorithm, globals(), locals(),
                                                     ['count'], 0)
        card = _handler.count(0, card, d_plan, Transaction())
        card.save()
        print('New discount = %s.' % card.discount)

Exemplo n.º 22
0
def count(value, card, d_plan, transaction):
    try:
        parameters = json.loads(d_plan.parameters)
    except:
        return None
    if type(parameters) is not dict:
        return None
    value = float(value)

    if 'bonus_mechanism' in parameters:
        bonus_mechanism = parameters['bonus_mechanism']
    else:
        return None

    if bonus_mechanism == 'bonus_cost':
        if 'bonus_cost' in parameters:
            bonus_cost = float(parameters['bonus_cost'])
        else:
            return None

    if bonus_mechanism == 'bonus_percent':
        if 'bonus_percent' in parameters:
            bonus_percent = float(parameters['bonus_percent'])
        else:
            return None

    if 'min_transaction' in parameters:
        min_transaction = float(parameters['min_transaction'])
    else:
        return None

    if 'bonus_lifetime' in parameters:
        bonus_lifetime = float(parameters['bonus_lifetime'])
    else:
        return None

    if 'round' in parameters:
        rounding = parameters['round']
    else:
        return None

    if abs(value) < min_transaction:
        return card

    bonus = Bonus()
    bonus.date = transaction.date
    bonus.active_from = datetime.now() + relativedelta(days=d_plan.time_delay)
    bonus.card = card
    if bonus_mechanism == 'bonus_cost':
        bonus.value = custom_round((value / bonus_cost), rounding)
    elif bonus_mechanism == 'bonus_percent':
        bonus.value = custom_round((value * bonus_percent / 100), rounding)

    bonus.active_to = bonus.active_from + relativedelta(
        months=int(bonus_lifetime))

    bonus.enabled = False
    bonus.transaction_id = transaction.pk

    trans = Transaction(org=card.org,
                        card=card,
                        date=datetime.now(),
                        bonus_before=card.get_total_bonus(),
                        doc_number=transaction.doc_number,
                        session=transaction.session,
                        sum=transaction.sum,
                        shop=transaction.shop,
                        workplace=transaction.workplace)

    if value < 0:
        trans.type = Operations.bonus_refund
        refund_bonus(card, transaction.base_doc_date, -bonus.value)
        trans.bonus_add = bonus.value
        trans.save()

        return card
    else:
        trans.type = Operations.bonus_add

    trans.bonus_add = bonus.value
    trans.save()

    task = Task(queue_date=datetime.now(),
                execution_date=datetime.now().date() +
                relativedelta(days=d_plan.time_delay),
                data=transaction.sum,
                card=card,
                operation="bonus",
                d_plan=d_plan,
                transaction=trans,
                org=card.org)
    task.save()
    bonus.task_id = task.pk

    bonus.save()

    return card
Exemplo n.º 23
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.º 24
0
def create_series(request):
    current_user = request.user

    if request.method == "POST":
        form = CreateSeriesForm(current_user.id, data=request.POST)

        if form.is_valid():
            series = form.save()
            series.start_datetime = timezone.make_aware(
                datetime.combine(form.cleaned_data["start_date"],
                                 form.cleaned_data["start_time"]))
            series.teacher = current_user
            series.save()

            students = form.cleaned_data["students"]

            if series.repeat == Series.RepeatChoices.NEVER:
                delta = None

            elif series.repeat == Series.RepeatChoices.DAILY:
                delta = timedelta(days=1)

            elif series.repeat == Series.RepeatChoices.WEEKLY:
                delta = timedelta(days=7)

            # only RepeatChoice left is monthly
            else:
                delta = relativedelta(months=1)

            lesson_datetime = series.start_datetime
            # do-while loop implementation
            while True:
                lesson = Lesson(
                    series=series,
                    teacher=current_user,
                    datetime=lesson_datetime,
                    length=series.length,
                )
                lesson.save()
                lesson.students.set(students)

                for student in students:
                    student_status = StudentStatus(student=student,
                                                   lesson=lesson)
                    student_status.save()

                lesson_datetime += delta
                if lesson_datetime.date(
                ) > form.cleaned_data["end_date"] or not delta:
                    break

            if (amount := form.cleaned_data["amount"]):
                for student in students:
                    transaction_record = get_create_transaction_record(
                        current_user, student)

                    transaction = Transaction(
                        sender=current_user,
                        receiver=student,
                        last_sent_by=current_user,
                        transaction_record=transaction_record,
                        amount=amount,
                        note="fee for " + form.cleaned_data["name"],
                        series=series,
                    )
                    transaction.save()

            return HttpResponseRedirect(reverse("lesson_planner:index"))
Exemplo n.º 25
0
def createOrderId(em,plan,amount):
    t = Transaction(customer_email = em,customer_name=em.first_name+" "+em.last_name,customer_phone_number=em.phone_number,plan = plan,amount = amount,eligibility = json.dumps(cust_set.plan[plan]["details"]))
    t.save()
    print("saving")
    return str(t.order_id)
Exemplo n.º 26
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')
Exemplo n.º 27
0
def count(value, card, d_plan, transaction):
    # try:
    #     parameters = json.loads(d_plan.parameters)
    # except:
    #     return None
    # if type(parameters) is not dict:
    #     return None

    try:
        rules = json.loads(d_plan.rules)
    except:
        return None
    if type(rules) is not list:
        return None

    value = float(value)

    rules = DiscountParameters().load(rules)
    next_discount = None
    if value >= 0:
        while rules.current <= rules.last:
            if rules.get_current()[0] == card.discount:
                next_discount = rules.next()
                if next_discount is None:
                    return card
                if next_discount[1] <= card.accumulation:
                    card.discount = next_discount[0]

                    trans = Transaction(org=card.org,
                                        card=card,
                                        date=datetime.now(),
                                        type=Operations.discount_recount,
                                        bonus_add=card.discount,
                                        doc_number=transaction.doc_number,
                                        session=transaction.session,
                                        sum=transaction.sum,
                                        shop=transaction.shop,
                                        workplace=transaction.workplace)
                    trans.save()

                else:
                    return card
            else:
                rules.next()

    if value < 0:
        rules.current = rules.last
        while rules.current >= rules.first:
            if rules.get_current()[0] == card.discount:
                next_discount = rules.get_previous()
                if next_discount is None:
                    return card
                if rules.get_current()[1] > card.accumulation:
                    card.discount = next_discount[0]

                    trans = Transaction(org=card.org,
                                        card=card,
                                        date=datetime.now(),
                                        type=Operations.discount_recount,
                                        bonus_add=card.discount,
                                        doc_number=transaction.doc_number,
                                        session=transaction.session,
                                        sum=transaction.sum,
                                        shop=transaction.shop,
                                        workplace=transaction.workplace)
                    trans.save()

                else:
                    return card
            else:
                rules.previous()

    return card
Exemplo n.º 28
0
def startashipment(
    request,
    host_id=None,
    transaction_form_submitted=False,
    invoice=None,
    cal_form_submitted=False,
    packagedays_count=None,
):
    random3digits = random.randint(100, 999)
    #set timezone
    local_timezone = request.session.setdefault('django_timezone', 'UTC')
    local_timezone = pytz.timezone(local_timezone)
    enduser = request.user
    calendar_submit_button_text = "Select Dates and Proceed to Payment"
    if host_id:
        host = get_object_or_404(UserInfo, pk=host_id)
    else:
        host = None
    #Determine if payment is needed or balance will suffice
    balance = enduser.account_balance_packages
    if balance > 0:
        payment_needed = False
        amount_due = 0.00
        remaining_balance = balance - 1
    else:
        if enduser.betauser_free:
            payment_needed = False
        else:
            payment_needed = True
        amount_due = None  #this is processed on the payment page if they aren't applying account balance
        remaining_balance = None
    connections_all = Connection.objects.filter(end_user=enduser)
    #Empty variables for availability/ conflict stuff
    days_package_may_come_thismonth = []
    days_package_may_come_nextmonth = []
    month1days_count = None
    month2days_count = None
    conflicts_date_from = []
    conflicts_startmonths = []
    conflicts_startthismonth = []
    conflicts_startnextmonth = []
    conflicts_startandend_thismonth = []
    conflicts_startandend_nextmonth = []
    conflicts_startthismonth_endnextmonth = []
    conflicts_startthismonth_endlater = []
    conflicts_startnextmonth_endlater = []
    days_withconflicts_thismonth = []
    days_withconflicts_nextmonth = []
    days_withconflicts_later = []
    #if host/no host - get caklendar_homebrew created fields
    if host:
        transcount = Transaction.objects.filter(host=host).count(
        ) + 1  #counts transactions that this receiver_email has received (could change to host email)
        #invoice = "H" + str(host.id) + "U" + str(enduser.id) + "N" +str(transcount) +"D" + str(date_today.month) + str(date_today.day) + str(time.hour) + "R" + str(random3digits) #h2u14N13D112210R123 = transaciton between host2, user14, host's 13th transaction
        #JMY updating invoice algorithm - removing date to make it smaller
        invoice = "H" + str(
            host.id
        ) + "U" + str(enduser.id) + "N" + str(transcount) + "R" + str(
            random3digits
        )  #h2u14N13D112210R123 = transaciton between host2, user14, host's 13th transaction
        conflicts = HostConflicts_DateVersion.objects.filter(host=host)
        for conflict in conflicts:
            if conflict.month == thismonth_num:
                days_withconflicts_thismonth.append(conflict.day)
            if conflict.month == nextmonth_num:
                days_withconflicts_nextmonth.append(conflict.day)
        #i think i do this to remove duplicates
        days_withconflicts_thismonth = list(set(days_withconflicts_thismonth))
        days_withconflicts_nextmonth = list(set(days_withconflicts_nextmonth))
        #determine if there is a conflict
        host_package_conflict = False
        for day in days_package_may_come_thismonth:
            if day in days_withconflicts_thismonth:
                host_package_conflict = True
        for day in days_package_may_come_nextmonth:
            if day in days_withconflicts_nextmonth:
                host_package_conflict = True
    else:  #if no host specified that stuff is empty/none
        conflicts = None
        host_package_conflict = False
    #do payment variables/ transaction form stuff once they've checked the calendar day
    favortype = 'package'
    #transaction_form_submitted = False
    #packagedays_count = None
    if cal_form_submitted:
        cal_form = CalendarCheckBoxes()
        packagedays = None
        packagedays_string = None
        trans_form_package = None
        trans = Transaction()
        #request.method = 'GET'
        if request.method == 'POST':
            trans_form_package = CreatePackageTransaction(request.POST)
            if trans_form_package.is_valid():
                title = trans_form_package.cleaned_data['title']
                payment_option = trans_form_package.cleaned_data[
                    'payment_option']
                note_to_host = trans_form_package.cleaned_data['note_to_host']
                paypal_quantity = 1
                if payment_option == "bundle10":
                    price = host.price_package_bundle10
                    youselected = "Bundle of 10 Packages"
                    balance_created = 9  #10 minus the 1 they just bought
                elif payment_option == "bundle20":
                    price = host.price_package_bundle20
                    youselected = "Bundle of 20 Packages"
                    balance_created = 19  #20 minus the 1 they just bought
                elif payment_option == "annual":
                    price = host.price_package_annual
                    youselected = "Annual"
                    balance_created = 1000  #Notional - this option is not in place currently
                else:
                    price = host.price_package_per
                    youselected = "Per Package"
                    balance_created = None
                #Next, add the data to the transaction table
                trans.balance_created_packages = balance_created
                trans.payment_option = payment_option
                trans.title = title
                trans.favortype = favortype
                trans.note_to_host = note_to_host
                trans.price = price
                trans.youselected = youselected
                trans.paypal_quantity = paypal_quantity
                trans.host = host
                trans.enduser = enduser
                trans.invoice = invoice
                #Account balance/ create amount_due
                if enduser.account_balance_packages:
                    if enduser.account_balance_packages > 0:
                        trans.amount_due = 0
                        trans.payment_needed = False
                    else:
                        trans.amount_due = price
                        trans.payment_needed = True
                else:
                    trans.amount_due = price
                    trans.payment_needed = True
                arrivalwindow_days_count = trans_form_package.cleaned_data[
                    'packagedays_count']
                trans.arrivalwindow_days_count = arrivalwindow_days_count
                day1 = trans_form_package.cleaned_data['arrivalwindow_day1']
                day1string = trans_form_package.cleaned_data[
                    'arrivalwindow_day1string']
                if day1:
                    trans.arrivalwindow_day1 = day1
                day2 = trans_form_package.cleaned_data['arrivalwindow_day2']
                day2string = trans_form_package.cleaned_data[
                    'arrivalwindow_day2string']
                if day2:
                    trans.arrivalwindow_day2 = day2
                day3 = trans_form_package.cleaned_data['arrivalwindow_day3']
                day3string = trans_form_package.cleaned_data[
                    'arrivalwindow_day3string']
                if day3:
                    trans.arrivalwindow_day3 = day3
                day4 = trans_form_package.cleaned_data['arrivalwindow_day4']
                day4string = trans_form_package.cleaned_data[
                    'arrivalwindow_day4string']
                if day4:
                    trans.arrivalwindow_day4 = day4
                day5 = trans_form_package.cleaned_data['arrivalwindow_day5']
                day5string = trans_form_package.cleaned_data[
                    'arrivalwindow_day5string']
                if day5:
                    trans.arrivalwindow_day5 = day5
                day6 = trans_form_package.cleaned_data['arrivalwindow_day6']
                day6string = trans_form_package.cleaned_data[
                    'arrivalwindow_day6string']
                if day6:
                    trans.arrivalwindow_day6 = day6
                day7 = trans_form_package.cleaned_data['arrivalwindow_day7']
                day7string = trans_form_package.cleaned_data[
                    'arrivalwindow_day7string']
                if day7:
                    trans.arrivalwindow_day7 = day7
                if arrivalwindow_days_count == 1:
                    trans.arrivalwindow_string = str(day1string)
                    trans.arrivalwindow_lastday = day1
                if arrivalwindow_days_count == 2:
                    trans.arrivalwindow_string = str(
                        day1string) + " or " + str(day2string)
                    trans.arrivalwindow_lastday = day2
                if arrivalwindow_days_count == 3:
                    trans.arrivalwindow_string = str(day1string) + ", " + str(
                        day2string) + ", or " + str(day3string)
                    trans.arrivalwindow_lastday = day3
                if arrivalwindow_days_count == 4:
                    trans.arrivalwindow_string = str(day1string) + ", " + str(
                        day2string) + ", " + str(day3string) + ", or " + str(
                            day4string)
                    trans.arrivalwindow_lastday = day4
                if arrivalwindow_days_count == 5:
                    trans.arrivalwindow_string = str(day1string) + ", " + str(
                        day2string) + ", " + str(day3string) + ", " + str(
                            day4string) + ", or " + str(day5string)
                    trans.arrivalwindow_lastday = day5
                if arrivalwindow_days_count == 6:
                    trans.arrivalwindow_string = str(day1string) + ", " + str(
                        day2string) + ", " + str(day3string) + ", " + str(
                            day4string) + ", " + str(
                                day5string) + ", or " + str(day6string)
                    trans.arrivalwindow_lastday = day6
                if arrivalwindow_days_count == 7:
                    trans.arrivalwindow_lastday = day7
                    trans.arrivalwindow_string = str(day1string) + ", " + str(
                        day2string) + ", " + str(day3string) + ", " + str(
                            day4string) + ", " + str(day5string) + ", " + str(
                                day6string) + ", or " + str(day7string)
                trans.save()
                transaction_form_submitted = True
            else:
                print trans_form_package.errors
                transaction_form_submitted = False
                errors_on_trans_form = 'There are errors on the transaction form'
        else:
            trans_form_package = CreatePackageTransaction()
            transaction_form_submitted = False
            errors_on_trans_form = 'Method is not POST'
    #if cal_form_submitted is false
    else:
        transaction_form_submitted = False
        errors_on_trans_form = 'Cal_form was not submitted'
        trans_form_package = None
        transaction_form_submitted = False
        packagedays = []
        packagedays_string = []
        #do the cal_form submission stuff
        if request.method == 'POST':
            cal_form = CalendarCheckBoxes(data=request.POST)
            if cal_form.is_valid():
                for daynumber in range(
                        1,
                        32):  #starts at zero otherwise so this will stop at 31
                    daycheckedmonth1 = cal_form.cleaned_data['month1day' +
                                                             str(daynumber)]
                    if daycheckedmonth1:
                        #checked day needs to be in YYYY-MM-DD  format
                        checked_day = str(thisyear) + "-" + str(
                            thismonth_num) + "-" + str(daynumber)
                        checked_day_string = str(thismonth) + " " + str(
                            daynumber)
                        packagedays.append(checked_day)
                        packagedays_string.append(checked_day_string)
                        days_package_may_come_thismonth.append(daynumber)
                for daynumber in range(1, 32):
                    daycheckedmonth2 = cal_form.cleaned_data['month2day' +
                                                             str(daynumber)]
                    if daycheckedmonth2:
                        checked_day = str(nextmonth_calendar_year) + "-" + str(
                            nextmonth_num) + "-" + str(daynumber)
                        checked_day_string = str(nextmonth) + " " + str(
                            daynumber)
                        packagedays.append(checked_day)
                        packagedays_string.append(checked_day_string)
                        days_package_may_come_nextmonth.append(daynumber)
                month1days_count = len(days_package_may_come_thismonth)
                month2days_count = len(days_package_may_come_nextmonth)
                cal_form_submitted = True
            else:
                print cal_form.errors
        else:
            cal_form = CalendarCheckBoxes()
        packagedays_count = len(packagedays)
    #if the transaction form has been submitted redirect to new page
    if transaction_form_submitted == True:
        cal_form = None
        if payment_needed:
            return HttpResponseRedirect("/transactions/payment/host" +
                                        str(host.id) + "/invoice" +
                                        str(invoice) + "/favortype" +
                                        str(favortype) + "/")
        else:
            return HttpResponseRedirect("/transactions/shippackage/host" +
                                        str(host.id) +
                                        "/account_balance/invoice" +
                                        str(invoice) + "/")
    #if the transaction form has not been submitted
    else:
        return render(
            request,
            'blocbox/startashipment.html',
            {
                'enduser': enduser,
                'host': host,
                'connections_all': connections_all,
                #'cal_relations_host_count': cal_relations_host_count, 'cal_relations_host': cal_relations_host, 'cal_list_host': cal_list_host,
                'here': quote(request.get_full_path()),
                #Python calendar variables (independent of conflict app)
                'local_timezone': local_timezone,
                'date_today': date_today,
                'datetime_now': datetime_now,
                'thisyear': thisyear,
                'nextyear': nextyear,
                'thisyeaer_isleap': thisyear_isleap,
                'nextyear_isleap': nextyear_isleap,
                'thismonth': thismonth,
                'nextmonth': nextmonth,
                'thismonth_calendar': thismonth_calendar,
                'nextmonth_calendar': nextmonth_calendar,
                'monthrange_thismonth': monthrange_thismonth,
                'monthrange_nextmonth': monthrange_nextmonth,
                'days_in_thismonth': days_in_thismonth,
                'days_in_nextmonth': days_in_nextmonth,
                'today_dayofmonth_num': today_dayofmonth_num,
                'nextmonth_calendar_year': nextmonth_calendar_year,
                #conflict app variables (if host)
                'conflicts': conflicts,
                'conflicts_startthismonth': conflicts_startthismonth,
                'conflicts_startnextmonth': conflicts_startnextmonth,
                'conflicts_startandend_thismonth':
                conflicts_startandend_thismonth,
                'conflicts_startandend_nextmonth':
                conflicts_startandend_nextmonth,
                'days_withconflicts_thismonth': days_withconflicts_thismonth,
                'days_withconflicts_nextmonth': days_withconflicts_nextmonth,
                #days package may come
                'days_package_may_come_thismonth':
                days_package_may_come_thismonth,
                'days_package_may_come_nextmonth':
                days_package_may_come_nextmonth,
                'host_package_conflict': host_package_conflict,
                #Calendar check boxes form
                'cal_form': cal_form,
                'packagedays': packagedays,
                'packagedays_string': packagedays_string,
                'packagedays_count': packagedays_count,
                'cal_form_submitted': cal_form_submitted,
                'calendar_submit_button_text': calendar_submit_button_text,
                #payment stuff once the calendar checkboxes are checked
                'trans_form_package': trans_form_package,
                'invoice': invoice,
                'favortype': favortype,
                'errors_on_trans_form': errors_on_trans_form,
                'transaction_form_submitted': transaction_form_submitted,
                'random3digits': random3digits,
                'payment_needed': payment_needed,
                'amount_due': amount_due,
                'remaining_balance': remaining_balance,
                'request': request,
            })
Exemplo n.º 29
0
                                       line.replace(why_prefix, ''))
            elif line.startswith(when_prefix):
                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])
Exemplo n.º 30
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')