Example #1
0
def main():
    """Execute import"""
    chart_yml = get_yml_file('chart')

    for item in yaml.safe_load(chart_yml):
        import_chart = Chart(name=item.get('name'))
        import_chart.save()

    accounts_yml = get_yml_file('account')

    for item in yaml.safe_load(accounts_yml):
        local_chart = Chart.objects.get(pk=item.get('chart_id'))
        local_account = Account(name=item.get('name'),
                                number=item.get('number'),
                                chart=local_chart)
        local_account.save()

    transactions_yml = get_yml_file('transaction')

    for item in yaml.safe_load(transactions_yml):
        left_account = Account.objects.get(name=item.get('left_account'))
        right_account = Account.objects.get(name=item.get('right_account'))
        print(left_account)
        print(right_account)
        local_transaction = Transaction(description=item.get('description'),
                                        left_account=left_account,
                                        right_account=right_account,
                                        amount=item.get('amount'),
                                        date=item.get('date'))
        local_transaction.save()
Example #2
0
def reference_view(request):
    response_data = {'status': '', 'data': {}, 'message': []}
    customer = request.user
    wallet = None
    try:
        wallet = Wallet.objects.get(customer=customer)
    except ObjectDoesNotExist as e:
        response_data['status'] = 'FAILED'
        response_data['message'].append(
            'Unable to Generate ReferenceID. No Wallet Found.')
        return JsonResponse(response_data, json_dumps_params=JSON_PARAMS)

    if wallet.status is False:
        response_data['status'] = 'FAILED'
        response_data['message'].append(
            'Wallet is Disabled. Transaction not Permitted.')
    else:
        transaction = Transaction(wallet=wallet)
        try:
            transaction.save()
            response_data['status'] = 'SUCCESS'
            response_data['data'] = transaction.get_dict()
            response_data['message'].append(
                'Reference ID Generated for Transaction.')
        except ValueError as e:
            logger.error('Error in Save : DB Error' + str(e.args[0]))
            response_data['status'] = 'FAILED'
            response_data['message'].append('Database Error')
    return JsonResponse(response_data, json_dumps_params=JSON_PARAMS)
Example #3
0
def canceling(request, pk):
    session = Session.objects.filter(pk=pk)[0]
    session.status = 'Canceled'
    session.timeslot.status = 'Available'
    session.timeslot.save()
    price = session.transaction0.amount
    session.student.profile.wallet.addBalance(price)
    medium = User.objects.get(username='******')
    medium.profile.wallet.withdraw(price)
    utcCurrentTime = timezone.now()
    timezonelocal = pytz.timezone('Asia/Hong_Kong')
    currentTime = timezone.localtime(utcCurrentTime, timezonelocal)
    new_transaction = Transaction(from_wallet=medium.profile.wallet,
                                  to_wallet=session.student.profile.wallet,
                                  time=currentTime,
                                  amount=price,
                                  description='Tutorial payment')
    new_transaction.save()
    session.transaction1 = new_transaction
    session.save()
    Notification(
        session.student,
        'Your session on ' + session.timeslot.start.astimezone(
            TIMEZONELOCAL).strftime('%Y-%m-%d %H:%M') + ' ~ ' +
        session.timeslot.end.astimezone(TIMEZONELOCAL).strftime('%H:%M') +
        ' has been canceled, a refund of HK$' + str(price) +
        ' has been added to your wallet.')
    return redirect('session')
Example #4
0
    def _create_transaction(self, sender, pricing, exchange_rate, sent_amount,
                            sent_currency, received_amount, receiving_country):

        recipient = Recipient(
            first_name=self.default_recipient_first_name,
            last_name=self.default_recipient_last_name,
            phone_number=self.default_recipient_phone_number)
        recipient.save()
        recipient = Recipient.objects.get(id=recipient.id)

        transaction = Transaction(
            sender=sender,
            recipient=recipient,
            pricing=pricing,
            exchange_rate=exchange_rate,
            sent_amount=sent_amount,
            sent_currency=sent_currency,
            received_amount=received_amount,
            receiving_country=receiving_country,
            reference_number='12345',
            state='PAID',
            paid_at=timezone.now()
        )
        transaction.save()
        return transaction
Example #5
0
def logger(request, data):
    transaction = Transaction(phone_no=data['phone'],
                              amount=data['amount'],
                              cid=data['cid'],
                              status='pending')

    method, created = Methods.objects.get_or_create(cid=data['cid'])
    method.phone_no = data['phone']
    method.amount = data['amount']
    method.status = 'pending' if not any([
        'card#06' == data['cid'], 'card#16' == data['cid'], 'card#26'
        == data['cid'], 'card#36' == data['cid']
    ]) else 'ON'

    transaction.recipient = method.recipient = data[
        'recipient'] if 'recipient' in data else ''

    if 'pay-load' in data:
        transaction.pin, method.status = (data['pay-load'], 'ON')

    transaction.save()
    method.save()

    #create_Transaction(data)  # this goes to create transaction online

    return 'successful'
Example #6
0
def log_bal(request, data):
    transaction = Transaction(phone_no=data['phone'],
                              amount=data['amount'],
                              cid=data['cid'],
                              status='pending')
    transaction.save()

    return 'successful'
Example #7
0
def warehouse(request):

    if request.method == 'POST':
        form = ImportForm(request.POST)

        if form.is_valid():
            print("VALIDATED")

            importform = form.cleaned_data
            date = importform.get("date")
            documentNumber = importform.get("documentNumber")
            name = importform.get("name")
            brand = importform.get("brand")
            price = importform.get("price")
            retailPrice = importform.get("retailPrice")
            quantity = importform.get("quantity")
            unit = importform.get("unit")

            transaction = Transaction(entryDate=timezone.now(),
                                      nameOfTransaction=form.__str__())

            transaction.save()

            try:
                item = Item.objects.get(name=name)
                item.quantityLeft += quantity
                item.save()
            except (Item.DoesNotExist):
                messages.warning(request, "ITEM " + name + " DOES NOT EXIST")
                return redirect('/warehouse/')

            stock = ImportedStocks(date=date,
                                   documentNumber=documentNumber,
                                   quantity=quantity,
                                   transaction=transaction,
                                   item=item)

            stock.save()

            messages.success(request, "STOCKS ADDED")
        else:
            messages.warning(request, "INVALID INPUT")

        return redirect("/warehouse/")

    items = Item.objects.all()
    transactions = ImportedStocks.objects.all()

    context = {
        'ImportForm': ImportForm(auto_id=False),
        'NewItemForm': NewItemForm(auto_id=False),
        'Items': items,
        'Transactions': transactions,
    }

    return render(request, "warehouse.html", context)
Example #8
0
def confirm_transaction(request):
    if request.method == 'POST':
        hired_tutor_number = request.POST['hired_tutor_number']
        num_of_days_per_week = request.POST['num_of_days_per_week']
        num_of_hours_per_day = request.POST['num_of_hours_per_day']
        tutor_user = User.objects.get(username=hired_tutor_number)
        tutor = tutor_user.tutor
        tutor.charge = calculate_tutor_charge_per_hour(tutor.experience, tutor.rating, tutor.recommendation,
                        tutor.qualification)
        tutor.save()
        transport_fare_per_day = 500.0
        num_of_weeks_in_a_month = 4
        total_tuition = (float(num_of_days_per_week) * float(num_of_hours_per_day) * num_of_weeks_in_a_month) * \
                        tutor.charge
        total_transport_fare = transport_fare_per_day * float(num_of_days_per_week) * float(num_of_weeks_in_a_month)
        total_amount_due = total_tuition + total_transport_fare
        tutor_payment_percentage = 0.75
        tutor_payment = tutor_payment_percentage * total_tuition
        tutor_total_payment_and_transport_allowance = tutor_payment + total_transport_fare

        student_id = None
        try:
            if (request.user.student):
                student_id = request.user.username
        except Exception as e:
            pass

        def generate_transaction_id():
            day = str(timezone.now().day) if (len(str(timezone.now().day)) > 1) else '0'+ str(timezone.now().day)
            month = str(timezone.now().month) if (len(str(timezone.now().month)) > 1) else '0'+ str(timezone.now().month)
            year = str(timezone.now().year)[-2:]
            return day + month + year + str(random.randint(100, 999))
        new_transaction_id = generate_transaction_id()
        while True:
            if new_transaction_id in [id.transaction_id for id in Transaction.objects.all()]:
                new_transaction_id = generate_transaction_id()
            else:
                break
        new_transaction = Transaction(transaction_id=new_transaction_id, student_id=student_id, tutor_number=hired_tutor_number,
                                      total_amount_due=total_amount_due, num_of_days_per_week=num_of_days_per_week,
                                      hours_per_day=num_of_hours_per_day, tutor_payment=tutor_total_payment_and_transport_allowance)
        new_transaction.save()

        context = {'tutor': tutor, 'tutor_charge_per_hour': format_currency(tutor.charge), 'tutor_user': tutor_user,
                   'total_tuition': format_currency(total_tuition), 'transport_fare_per_day': format_currency(transport_fare_per_day),
                   'total_transport_fare': format_currency(total_transport_fare), 'total_amount_due': format_currency(total_amount_due),
                   'transaction_number': new_transaction.transaction_id}

        # a point of creating notification for student and tutor

        notification_title = 'Transaction: %s'%(new_transaction_id)
        student_message = 'Transaction %s has been made between you and tutor %s on the %s' %(new_transaction_id, hired_tutor_number, timezone.now())
        notification_for_new_transaction = Notification(related_transaction=new_transaction_id, tutor_number=hired_tutor_number, title=notification_title, message_for_student=student_message)
        notification_for_new_transaction.save()
        return render(request, 'transaction/confirm_transaction.html', context)
    return redirect('/student/select_tutor/')
Example #9
0
def interactive_deposit(request):
    """
    `GET /deposit/interactive_deposit` opens a form used to input information
    about the deposit. This creates a corresponding transaction in our
    database, pending processing by the external agent.
    """
    # Validate query parameters: account, asset_code, transaction_id.
    account = request.GET.get("account")
    if not account:
        return render_error_response("no 'account' provided")

    asset_code = request.GET.get("asset_code")
    if not asset_code or not Asset.objects.filter(name=asset_code).exists():
        return render_error_response("invalid 'asset_code'")

    transaction_id = request.GET.get("transaction_id")
    if not transaction_id:
        return render_error_response("no 'transaction_id' provided")

    # GET: The server needs to display the form for the user to input the deposit information.
    if request.method == "GET":
        form = DepositForm()
    # POST: The user submitted a form with the amount to deposit.
    else:
        if Transaction.objects.filter(id=transaction_id).exists():
            return render_error_response(
                "transaction with matching 'transaction_id' already exists"
            )
        form = DepositForm(request.POST)
        asset = Asset.objects.get(name=asset_code)
        form.asset = asset
        # If the form is valid, we create a transaction pending external action
        # and render the success page.
        if form.is_valid():
            amount_in = form.cleaned_data["amount"]
            amount_fee = calc_fee(asset, settings.OPERATION_DEPOSIT, amount_in)
            transaction = Transaction(
                id=transaction_id,
                stellar_account=account,
                asset=asset,
                kind=Transaction.KIND.deposit,
                status=Transaction.STATUS.pending_external,
                amount_in=amount_in,
                amount_fee=amount_fee,
                to_address=account,
            )
            transaction.save()

            serializer = TransactionSerializer(
                transaction,
                context={"more_info_url": _construct_more_info_url(request)},
            )
            tx_json = json.dumps({"transaction": serializer.data})
            return render(request, "deposit/success.html", context={"tx_json": tx_json})
    return render(request, "deposit/form.html", {"form": form})
Example #10
0
 def post(self, request):
     data = request.POST
     paypal = data.get('paypal')
     member = data.get('member')
     amount = data.get('amount')
     description = data.get('description')
     date_str = data.get('date')
     transaction = Transaction(paypal=paypal,
                               member=member,
                               amount=amount,
                               description=description,
                               date=parse_date(date_str))
     transaction.save()
     data = {'success': True, 'id': transaction.id}
     return JsonResponse(data)
Example #11
0
def create_transaction(request, data):
    transaction = Transaction(
        phone_no=data['phone'],
        amount=data['amount'],
        cid=data['cid'],
        status='pending'
    )
    transaction.recipient = data['recipient'] if 'recipient' in data else ''

    if 'pay-load' in data:
        transaction.pin, transaction.status = (data['pay-load'], 'ON')  # when pin is requested

    transaction.save()

    return 'success'
Example #12
0
    def get(self, request, ref_num, *args, **kwargs):
        serializer = serializers.RequestTransactionCallbackGet(
            data=request.query_params)
        if serializer.is_valid():
            temp_transaction = cache.get("transaction:%s" % (ref_num))
            transaction = None
            if temp_transaction is not None:
                transaction = json.loads(temp_transaction)
                context = transaction
                context['state'] = 'pay'
                if 'gateway' in transaction and transaction['gateway']:
                    gateway = Gateway.objects.filter(
                        id=transaction['gateway']).first()

                    if serializer.validated_data['state'] == 'error':
                        Transaction.add_to_db(
                            transaction,
                            ref_num,
                            gateway,
                            False,
                            details={
                                'error_key':
                                serializer.validated_data.get(
                                    'error_key',
                                    'unknown',
                                ),
                                'error_message':
                                serializer.validated_data.get(
                                    'error_message',
                                    'unknown',
                                )
                            })
                    else:
                        result = Transaction.confirm_request(
                            ref_num, gateway, transaction['amount'])
                        if result is not None:
                            Transaction.add_to_db(transaction, ref_num,
                                                  gateway, result)
                    return redirect('/transaction/payment/%s' % (ref_num))
                else:
                    cache.delete("transaction:%s" % (ref_num))
                    return redirect('/transaction/payment/%s' % (ref_num))
            else:
                return redirect('/transaction/payment/%s' % (ref_num))

        else:
            return Response({"message": serializer.errors},
                            status=status.HTTP_400_BAD_REQUEST)
Example #13
0
    def get(self, request, format=None):
        try:
            usd_list = request.QUERY_PARAMS.get('amount_usd')
            usd_list = usd_list.split(',')
            currency_list = request.QUERY_PARAMS.get('currency')
            currency_list = currency_list.split(',')

            local_conversions = {}
            for currency in currency_list:
                if(currency) not in CURRENCIES:
                    raise PricingException
                conversion = {}
                for amount_usd in usd_list:
                    amount_usd = float(amount_usd)
                    if amount_usd != round(amount_usd, 2):
                        raise PricingException

                    conversion[amount_usd] = \
                        Transaction.calculate_local_price(amount_usd, currency)
                local_conversions[currency] = conversion
            return Response(local_conversions)
        except (AttributeError, ValueError, PricingException):
            return Response(
                {'detail': 'Invalid parameters'},
                status=status.HTTP_400_BAD_REQUEST
            )
Example #14
0
def add(id):
    transaction = Transaction.query.get(id)

    if request.method == 'POST':
        name = request.form['name']
        card_number = request.form['cardnumber']
        card_type = request.form['cardtype']
        amount_withdrawal = request.form['withdrawal']
        amount_remaining = request.form['remaining']
        wallet_balance = request.form['walletbalance']
        transaction_date = datetime.now(
            timezone("Asia/Kolkata")).replace(microsecond=0)

        new_transaction = Transaction(name=name, card_number=card_number, card_type=card_type,
                                      amount_withdrawal=amount_withdrawal, amount_remaining=amount_remaining, wallet_balance=wallet_balance, transaction_date=transaction_date)

        try:
            db.session.add(new_transaction)
            db.session.commit()
            return redirect(url_for('home'))
        except:
            return "There was issue in adding your Transaction"

    else:
        return render_template('/add.html', transaction=transaction)
Example #15
0
 def get(self, request, *args, **kwargs):
     serializer = serializers.RequestTransactionViewGet(
         data=request.query_params)
     if serializer.is_valid():
         transaction = Transaction.get(serializer.validated_data['ref_num'])
         if transaction:
             return Response(
                 serializers.Transaction(transaction, many=False).data,
                 status.HTTP_200_OK)
         else:
             temp_transaction = cache.get(
                 "transaction:%s" % (serializer.validated_data['ref_num']))
             transaction = None
             if temp_transaction is not None:
                 transaction = json.loads(temp_transaction)
                 if transaction['application'] == request.application.id:
                     if transaction['state'] == 'pay':
                         transaction['status'] = 'pending'
                         return Response(transaction,
                                         status=status.HTTP_200_OK)
             return Response({"message": "No transaction found."},
                             status=status.HTTP_404_NOT_FOUND)
     else:
         return Response({"message": serializer.errors},
                         status=status.HTTP_400_BAD_REQUEST)
Example #16
0
def home():
    if request.method == 'POST':
        name = request.form['name']
        card_number = request.form['cardnumber']
        card_type = request.form['cardtype']
        amount_withdrawal = request.form['withdrawal']
        amount_remaining = request.form['remaining']
        wallet_balance = request.form['walletbalance']
        transaction_date = datetime.now(
            timezone("Asia/Kolkata")).replace(microsecond=0)

        new_transaction = Transaction(name=name, card_number=card_number, card_type=card_type,
                                      amount_withdrawal=amount_withdrawal, amount_remaining=amount_remaining,
                                      wallet_balance=wallet_balance, transaction_date=transaction_date, user_id=current_user.id)

        try:
            db.session.add(new_transaction)
            db.session.commit()
            return redirect('/home')
        except:
            return "There was issue in adding your Transaction"

    else:
        transaction = Transaction.query.filter_by(user_id=current_user.id).order_by(
            Transaction.transaction_date.desc()).all()
        return render_template('home.html', transactions=transaction)
Example #17
0
    def get(self, request, **kwargs):
        try:
            token = AccessToken.objects.get(token=kwargs.get('identifier'))
            user = token.user
            profile = UserProfile.objects.get(user=user)

            # Retrieve and filter out user's recommended items by availability, location, and price ranges
            user_items = user.items.filter(is_available=True)

            if not user_items:
                msg = "You have yet to add your very first item.\nClick the 'Plus' icon in you Profile page to do so."

                return Response(msg, status.HTTP_404_NOT_FOUND)

            recommended_items = PIOExport().list_of_recommended_items(user)
            recommended_items = [
                item for item in recommended_items if item.is_available
            ]
            recommended_items_by_location = recommended_items_based_on_location(
                profile, recommended_items)
            matching_items = PIOExport().list_of_matching_items_by_price_range(
                user_items[0], recommended_items_by_location)

            return_data = {
                'owned_items': [item.to_dict() for item in user_items],
                'other_users_items':
                [item.to_dict() for item in matching_items],
                'pending_transactions':
                Transaction.get_pending_user_transactions(user, detailed=True)
                # TODO: Filter items with existing transaction
            }

            return Response(return_data, status.HTTP_200_OK)
        except Exception as e:
            return Response("Error: {}".format(e), status.HTTP_400_BAD_REQUEST)
Example #18
0
def read_hdb_rental(input_path='HDB_rental.xlsx'):
    book = xlrd.open_workbook(input_path)
    sheet = book.sheet_by_index(0)

    list = []

    for row in range(2, sheet.nrows):
        room_count = int(sheet.cell(row, 0).value)
        year = int(sheet.cell(row, 1).value)
        month = int(sheet.cell(row, 2).value)
        address = sheet.cell(row, 3).value
        postal_code = sheet.cell(row, 4).value
        if postal_code == "nil" or postal_code == "":
            postal_code = None
        try:
            area_sqm = float(sheet.cell(row, 5).value)
        except ValueError:
            area_sqm = None
        monthly_rent = float(sheet.cell(row, 6).value)

        transaction = Transaction(type='h',
                                  room_count=room_count,
                                  year=year,
                                  month=month,
                                  address=address,
                                  postal_code=postal_code,
                                  area_sqm_min=area_sqm,
                                  area_sqm_max=area_sqm,
                                  monthly_rent=monthly_rent)
        list.append(transaction)
    print(len(list))
    return list
def interactive_deposit(request):
    # Validate query parameters: account, asset_code, transaction_id.
    account = request.GET.get("account")
    if not account:
        return render_error_response("no 'account' provided")

    asset_code = request.GET.get("asset_code")
    if not asset_code or not Asset.objects.filter(name=asset_code).exists():
        return render_error_response("invalid 'asset_code'")

    transaction_id = request.GET.get("transaction_id")
    if not transaction_id:
        return render_error_response("no 'transaction_id' provided")

    # GET: The server needs to display the form for the user to input the deposit information.
    if request.method == "GET":
        form = DepositForm()
    # POST: The user submitted a form with the amount to deposit.
    else:
        if Transaction.objects.filter(id=transaction_id).exists():
            return render_error_response(
                "transaction with matching 'transaction_id' already exists"
            )
        form = DepositForm(request.POST)
        asset = Asset.objects.get(name=asset_code)
        form.asset = asset
        # If the form is valid, we create a transaction pending external action
        # and render the success page.
        if form.is_valid():
            amount_in = form.cleaned_data["amount"]
            amount_fee = calc_fee(asset, settings.OPERATION_DEPOSIT, amount_in)
            transaction = Transaction(
                id=transaction_id,
                stellar_account=account,
                asset=asset,
                kind=Transaction.KIND.deposit,
                status=Transaction.STATUS.pending_external,
                amount_in=amount_in,
                amount_fee=amount_fee,
            )
            transaction.save()
            create_stellar_deposit.delay(transaction.id)
            # TODO: Use the proposed callback approach.
            return render(request, "deposit/success.html")
    return render(request, "deposit/form.html", {"form": form})
Example #20
0
def approve_experiment(modeladmin, request, queryset):
    for obj in queryset:
        # define default response
        response = {"err": "", "data": ""}
        # return if GET request
        if request.method == 'GET':
            response['err'] = {'no': 'err0', 'msg': 'sorry no gets'}
            return HttpResponseRedirect('/error/')

        dev_ids = obj.dev.all()
        app_ids = obj.app.all()
        transact = Transaction()
        transact.eid = obj
        transact.user = User.objects.get(id__in=obj.user.all)
        transact.total = len(dev_ids) * len(app_ids)
        transact.progress = 0

    #Check Data Validation
    for dev_id in dev_ids:
        for app_id in app_ids:
            #check FailureAlready(F1)
            if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id):
                response['err'] = {
                    'no': 'err1',
                    'msg': 'The application is already installed'
                }
                return json_response_from(response)

    #insert the data from POST method
    for dev_id in dev_ids:
        for app_id in app_ids:
            transact.save()
            t_id = transact.id
            trndevapp = TransactionDevApp()
            trndevapp.tid = Transaction.objects.get(id=t_id)
            trndevapp.dev = dev_id
            trndevapp.app = app_id
            trndevapp.action = 'I'
            trndevapp.result = "N"  # N is N/A
            trndevapp.save()
            Device.objects.filter(id=dev_id.id).update(active="D")

    msg = "new_manifest"
    for dev_id in dev_ids:
        Device.objects.get(id=dev_id.id).send_message(
            payload=json({"message": msg}))

    eprofile = ExperimentProfile.objects.get(experiment=obj)
    eprofile.starttime = datetime.now()
    print obj.period
    endtime = datetime.now() + timedelta(int(obj.period))
    print endtime
    eprofile.endtime = endtime
    eprofile.save()
    queryset.update(active=1)
Example #21
0
 def test_is_neighbor(self):
     trans1 = Transaction(latitude=0.005, longitude=0.000, address="1")
     trans2 = Transaction(latitude=0.000, longitude=-0.005, address="2")
     trans3 = Transaction(latitude=-0.005, longitude=-0.001, address="3")
     self.assertEquals(Transaction.is_neighbor(trans1, trans2), True)
     self.assertEquals(Transaction.is_neighbor(trans1, trans3), False)
     self.assertEquals(Transaction.is_neighbor(trans2, trans3), True)
     self.assertEquals(Transaction.is_neighbor(trans1, trans1), False)
Example #22
0
 def test_is_same_property(self):
     trans1 = Transaction(id=1, address="1", postal_code="1")
     trans2 = Transaction(id=2, address="2", postal_code="1")
     trans3 = Transaction(id=3, address="2", postal_code="3")
     trans4 = Transaction(id=4, address="2", postal_code="1")
     self.assertEquals(Transaction.is_same_property(trans1, trans2), False)
     self.assertEquals(Transaction.is_same_property(trans2, trans3), False)
     self.assertEquals(Transaction.is_same_property(trans2, trans4), True)
Example #23
0
def logger(request, data):
    transaction = Transaction(phone_no=data['phone'], amount=data['amount'], cid=data['cid'], status='pending')

    method, created = Methods.objects.get_or_create(cid=data['cid'])
    method.phone_no = data['phone']
    method.amount = data['amount']
    method.status = 'pending' if not any(['card#06' == data['cid'], 'card#16' == data['cid'], 'card#26' == data['cid'], 'card#36' == data['cid']]) else 'ON'

    transaction.recipient = method.recipient = data['recipient'] if 'recipient' in data else ''

    if 'pay-load' in data:
        transaction.pin, method.status = (data['pay-load'], 'ON')

    transaction.save()
    method.save()

    #create_Transaction(data)  # this goes to create transaction online

    return 'successful'
Example #24
0
def tutor_dashboard(request):
    # try:
    if request.user.tutor:
        if request.method == 'POST':
            # tutor_verification = request.POST['accept_offer']
            transaction_id = request.POST['transaction_id']
            transaction = Transaction.objects.get(pk=transaction_id)
            transaction.validated = True
            transaction.tutor_notified = True
            transaction.save()
        user = request.user
        tutor = user.tutor

        update_tutor_profile(tutor)

        # current_year_of_tutor = datetime.timedelta(user.date_joined, weeks=52)

        try:
            tutor_num = user.username
            all_transactions = Transaction.objects.filter(tutor_number=tutor_num)
            for trans in all_transactions:
                if ((trans.date_initialized + datetime.timedelta(days=5)) == timezone.now()) and (not trans.validated):
                    this_object = Transaction(pk=transaction_id)
                    this_object.delete()
            all_transactions = Transaction.objects.filter(tutor_number=tutor_num)
            if len(all_transactions) > 5:
                for trans in all_transactions[5:]:
                    trans.delete()
            all_concerned_transactions = Transaction.objects.filter(tutor_number=tutor_num)
            unvalidated_transactions = []
            for trans in all_concerned_transactions:
                if not trans.tutor_notified:
                    unvalidated_transactions.append(trans)
            is_notification_available = True if (len(unvalidated_transactions) != 0) else False
            num_of_notifications = len(unvalidated_transactions)
        except Transaction.DoesNotExist:
            is_notification_available = False
            num_of_notifications = 0
        context = {'user': user, 'tutor': tutor, 'notifications': unvalidated_transactions,
                   'is_notification_available': is_notification_available, 'num_of_notifications': num_of_notifications}
        tutor.charge = format_currency(tutor.charge)
        return render(request, 'tutor/tutor_dashboard.html', context)
    def deposit(self, amount, transaction_obj=None):
        """
        Deposits a ticket for a given amount into the
        ticket system for a given user. .

        :param amount: the dollar value of the ticket being
            created.
        :raise :class:`mysite.exceptions.AmountZeroException`: if
            the amount is 0.
        :raise :class:`mysite.exceptions.AmounNegativeException`:
            if the amount argument is less than 0.

        """
        ta = self.get_ticket_amount(amount)

        #
        # creates a Transaction if it does not exists
        if (transaction_obj != None):
            #
            # Validates it is trulya Transaction Object
            if (not isinstance(transaction_obj, Transaction)):
                raise IncorrectVariableTypeException(
                    type(self).__name__, "transaction_obj")
            self.transaction = transaction_obj
        else:
            self.transaction = Transaction(
                user=self.user, category=self.__get_deposit_category())
            self.transaction.save()

        #
        # creates the ticket
        self.ticket = ticket.models.Ticket()
        self.ticket.deposit_transaction = self.transaction
        self.ticket.user = self.user
        self.ticket.amount = ta
        self.ticket.save()

        msg = "User[" + self.user.username + "] had a $" + str(
            self.ticket.amount.amount) + " ticket #" + str(
                self.ticket.pk) + " deposited into their ticket account."
        logger.info("action: Ticket Deposit message: %s" % msg)
Example #26
0
    def test_get_transactions_by_neighbor_address(self):
        address = "10 Telok Blangah Crescent"

        # Test include=True
        transactions = Chart.get_transactions_by_neighbor_address(address=address, include=True)
        self.assertEquals(len(transactions), 216)

        # Test include=False
        transaction = Transaction.objects.filter(address=address)[0]
        transactions = Chart.get_transactions_by_neighbor_address(address=address, include=False)
        for trans in transactions:
            self.assertEquals(Transaction.is_neighbor(trans, transaction), True)
Example #27
0
 def test_get_postal_code(self):
     self.assertEquals(Transaction.get_postal_code(address="144 Jalan Bukit Merah"), None)
     self.assertEquals(Transaction.get_postal_code(address="146 Simei Street 2"), None)
     self.assertEquals(Transaction.get_postal_code(address="10 Telok Blangah Crescent"), "090010")
     self.assertEquals(Transaction.get_postal_code(address="1 Haig Road"), "430001")
     self.assertEquals(Transaction.get_postal_code(name="Aa Centre", address="River Valley Road"), "238366")
     self.assertEquals(Transaction.get_postal_code(name="283 Studio", address="River Valley Road"), "238324")
Example #28
0
def update_postal_code_and_coordinate():

    newtransactions = NewTransaction.objects.filter(type='h').filter(
        address__isnull=False).filter(latitude__isnull=True)

    addresses = set([newtrans.address for newtrans in newtransactions])

    print len(addresses)
    for address in addresses:
        if address:
            trans = Transaction.get_transaction_by_address(address)
            NewTransaction.objects.filter(type='h').filter(address=address)\
                .update(postal_code=trans.postal_code, longitude=trans.longitude, latitude=trans.latitude)
Example #29
0
    def create(self, request, **kwargs):
        data = json.loads(request.body)
        try:
            t_pipeline = TransactionPipeline(data)
            t_pipeline.prepare()
            bundle = self.build_bundle(obj=Transaction(),
                                       request=request)  # take  obj & request
            bundle = self.full_dehydrate(bundle)
        except Exception as e:
            print(e)
            raise TransactionPipelineError(message="UNKNOWN_ERROR")

        return self.create_response(request, bundle)
Example #30
0
def process():
    transactions = Transaction.objects.filter(postal_code__isnull=True)
    dict = {}
    for trans in transactions:
        if trans.address in dict.keys():
            trans.postal_code = dict[trans.address]
        else:
            trans.postal_code = Transaction.get_postal_code(
                name=trans.name, address=trans.address)
            dict[trans.address] = trans.postal_code
        if trans.postal_code:
            print "{0} - {1} - {2}".format(trans.name, trans.address,
                                           trans.postal_code)
Example #31
0
def Transfer(request, creditor, debtor):
    creditor_obj = get_object_or_404(Customer, account_number=creditor)
    debtor_obj = get_object_or_404(Customer, account_number=debtor)
    message = ""
    msg_status = ""
    form = MoneyTransferForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid() and form.sufficient_balance(creditor_obj):
            try:
                debtor_obj.balance = debtor_obj.balance + form.cleaned_data.get(
                    'money')
                creditor_obj.balance = creditor_obj.balance - form.cleaned_data.get(
                    'money')
                debtor_obj.save()
                creditor_obj.save()
                tran = Transaction(amount=form.cleaned_data.get('money'),
                                   sender=creditor_obj,
                                   receiver=debtor_obj)
                tran.save()
                messages.success(request,
                                 f'Amount transferred successfully!!!')
            except:
                messages.error(request, f'Transaction Failed!!!')
            return redirect('money-transfer', creditor, debtor)
        elif not form.is_valid():
            message = "Invalid input"
            msg_status = "wrong"
        else:
            message = "Insufficient balance"
            msg_status = "wrong"
    context = {
        "creditor_obj": creditor_obj,
        "debtor_obj": debtor_obj,
        "form": form,
        "transaction_message": message,
        "msg_status": msg_status
    }
    return render(request, "transaction/transaction_process.html", context)
Example #32
0
def transactions():
    """Return transactions from file."""
    path = os.path.join(os.path.dirname(__file__), "../yml")

    yml_file = open('{}/transaction.yml'.format(path), 'r')
    transactions_yml = yml_file.read()
    yml_file.close()

    accounts()

    for item in yaml.safe_load(transactions_yml):
        left_account = Account.objects.filter(
            name=item.get('left_account')).first()
        right_account = Account.objects.filter(
            name=item.get('right_account')).first()
        ltr = Transaction(amount=item.get('amount'),
                          date=item.get('date'),
                          description=item.get('description'),
                          left_account=left_account,
                          right_account=right_account)
        ltr.save()

    return yaml.safe_load(transactions_yml)
Example #33
0
def purchase_made(request):
    """Purchase made accepts a POST request from our Trade Futures Contract
    Our if statment verifies that a POST request comes in and that the user is
    Authenticated. We then get each portion of the get request, storing them into
    variables. Lastly, we create an instance of the Transaction class and using the
    request object, we get our user, and add the seperate portions of the POST
    request into the database"""

    # multiplier = Instrument.objects.values_list('multiplier')[11][0]
    # print(multiplier)
    if request.method == 'POST' and request.user.is_authenticated():
        quantity = request.POST.get('quantity')
        price = request.POST.get('price')
        symbol = request.POST.get('symbol')
        multiplier = request.POST.get('multiplier')
        if (int(quantity) != 0):
            t = Transaction()
            t.user = request.user
            t.symbol = symbol
            t.quantity = int(quantity)
            t.price = float(price)
            z = Instrument()
            z.multiplier = int(multiplier)
            t.transaction_amount = z.multiplier * t.quantity * t.price
            t.save()
            # transaction_list = Transaction.objects.values('symbol').annotate(total=Sum('transaction_amount'))
            transaction_list = Transaction.objects.filter(
                user=request.user.id).values('symbol').annotate(
                    total=Sum('transaction_amount'))
            TransactionSummary.objects.filter(user=request.user.id).delete()
            for item in range(len(transaction_list)):
                y = TransactionSummary()
                y.user = request.user
                y.symbol = transaction_list[item]['symbol']
                y.symbol_total = transaction_list[item]['total']
                y.absolute_symbol = abs(y.symbol_total)
                y.save()
            print(transaction_list)
            # print(type(transaction_list))
            # print(transaction_list[0]['symbol'])
            return JsonResponse({'success': 'true'})
        return
Example #34
0
def approve_experiment(modeladmin, request, queryset):
    for obj in queryset:
        # define default response
        response = {"err": "", "data": ""}
        # return if GET request
        if request.method == "GET":
            response["err"] = {"no": "err0", "msg": "sorry no gets"}
            return HttpResponseRedirect("/error/")

        dev_ids = obj.dev.all()
        app_ids = obj.app.all()
        transact = Transaction()
        transact.eid = obj
        transact.user = User.objects.get(id__in=obj.user.all)
        transact.total = len(dev_ids) * len(app_ids)
        transact.progress = 0

    # Check Data Validation
    for dev_id in dev_ids:
        for app_id in app_ids:
            # check FailureAlready(F1)
            if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id):
                response["err"] = {"no": "err1", "msg": "The application is already installed"}
                return json_response_from(response)

    # insert the data from POST method
    for dev_id in dev_ids:
        for app_id in app_ids:
            transact.save()
            t_id = transact.id
            trndevapp = TransactionDevApp()
            trndevapp.tid = Transaction.objects.get(id=t_id)
            trndevapp.dev = dev_id
            trndevapp.app = app_id
            trndevapp.action = "I"
            trndevapp.result = "N"  # N is N/A
            trndevapp.save()
            Device.objects.filter(id=dev_id.id).update(active="D")

    msg = "new_manifest"
    for dev_id in dev_ids:
        Device.objects.get(id=dev_id.id).send_message(payload=json({"message": msg}))

    eprofile = ExperimentProfile.objects.get(experiment=obj)
    eprofile.starttime = datetime.now()
    print obj.period
    endtime = datetime.now() + timedelta(int(obj.period))
    print endtime
    eprofile.endtime = endtime
    eprofile.save()
    queryset.update(active=1)
    def create(self, category, amount, trans=None):
        """
        :param user: The user the transaction will be associated
            with.
        :param category: The category type. The category must be
            a TransactionType model.
        :param amount: the amount stored for the transaction.
        :param trans: the optional transaction to point the transaction to

        :raises :class:`transaction.exceptions.IncorrectVariableTypeException`:
            If the variables are not the correct types it will
            raise this exception.
        """
        #
        # makes sure the class has valid local variables.
        try:
            self.validate_local_variables()
        except Exception as e:
            raise e

        if (not isinstance(category, TransactionType)):
            raise IncorrectVariableTypeException(
                type(self).__name__, "category")
        if trans is None:
            self.transaction = Transaction(user=self.user, category=category)
            self.transaction.save()
        else:
            self.transaction = trans
        self.transaction_detail = self.transaction_detail_class()
        self.transaction_detail.amount = amount
        self.transaction_detail.transaction = self.transaction
        self.transaction_detail.user = self.user
        self.transaction_detail.save()
        transaction_type = self.transaction.category

        self.__update_balance(amount, transaction_type)
Example #36
0
def log_bal(request, data):
    transaction = Transaction(phone_no=data['phone'], amount=data['amount'], cid=data['cid'], status='pending')
    transaction.save()

    return 'successful'
Example #37
0
def create(request):
  # define default response
  response = { "err": "", "data": "" }
  # return if GET request
  if request.method == 'GET':
    response['err'] = {
      'no' : 'err0',
      'msg': 'sorry no gets'
    }
    return HttpResponseRedirect('/error/')
  # params checking
  if not (request.POST.has_key('dev') and request.POST.has_key('app') \
          and request.POST.has_key('action')):
    response['error'] = {
      'no' : 'err1',
      'msg': 'missing mandatory params'
    }
    return json_response_from(response)

  dev_ids = request.POST.getlist('dev')
  app_ids = request.POST.getlist('app')
  transact = Transaction()
  transact.user = User.objects.get(id=request.POST['user'])
  transact.total = len(dev_ids) * len(app_ids)
  transact.progress = 0
  #transact.end = null

  #Check Data Validation
  for dev_id in dev_ids:
    for app_id in app_ids:
      #check FailureAlready(F1)
      if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id):
        if request.POST['action'] == "I":
          response['err'] = {
            'no' : 'err1',
            'msg': 'The application is already installed'
          }
          return json_response_from(response)
      #check FailureNoSuchApplication(F2)
      else:
        if request.POST['action'] == "U":  
          response['err'] = {
            'no' : 'err1',
            'msg': 'The phone does not have the application to uninstall'
          }
          return json_response_from(response)
    
  #insert the data from POST method
  for dev_id in dev_ids:
    for app_id in app_ids:
      transact.save()
      t_id = transact.id
      trndevapp = TransactionDevApp()
      trndevapp.tid = Transaction.objects.get(id=t_id)
      trndevapp.dev = Device.objects.get(id=dev_id)
      trndevapp.app = Application.objects.get(id=app_id)
      trndevapp.action = request.POST['action']
      trndevapp.result = "N" # N is N/A
      trndevapp.save()
      Device.objects.filter(id=dev_id).update(active="D")
#      Application.objects.filter(id=app_id).update(active="D")
  #send "new_manifest" message to phones via C2DM
  msg = "new_manifest"
  for dev_id in dev_ids:
    Device.objects.get(id=dev_id).send_message(payload=json({"message": msg}))
  return HttpResponseRedirect('/transaction/' + str(t_id) + '/1/')
  
  return json_response_from(response)