Ejemplo n.º 1
0
def result(request):
    user = Customer.objects.get(user=request.user)
    amount = request.POST.get("amount")
    acc = request.POST.get("acc")
    acc = str(acc)
    t = Transaction(previous_balance=Decimal(user.balance))
    t.amount = Decimal(amount)
    user2 = Customer.objects.get(account_no=acc)
    u2 = User.objects.get(username=user2.user.username)
    print(type(u2))
    amount = Decimal(amount)
    t2 = Transaction(previous_balance=Decimal(user2.balance))
    t2.amount = Decimal(amount)
    a = user.get_balance(amount, 1)
    if a == -1:
        messages.error(request, "No Balance!")
        return HttpResponseRedirect(reverse('customer:profile'))
    else:
        user.balance = a
        user2.balance = user2.get_balance(amount, 2)
        user2.save()
        t2.current_balance = Decimal(user2.balance)
        t2.user = u2
        t2.save()
        t2.transaction_id = t2.get_transaction_id()
        t2.type = 'Account Transfer'
        t2.save()
    user.save()
    t.current_balance = Decimal(user.balance)
    t.user = request.user
    t.save()
    t.transaction_id = t.get_transaction_id()
    t.type = 'Account Transfer'
    t.save()
    return HttpResponseRedirect(reverse('customer:profile'))
Ejemplo n.º 2
0
def add_impress(request,firm_id):
    #delete_all()
    firm = Firm.objects.get(id=int(firm_id))
    firm_id = int(firm_id)
    if 'name' in request.session:
        ledger_name = request.session['name']
        del request.session['name']
        return render(request, 'transaction/add_impress.html',
                      {'name': firm.name, 'year': firm.year, 'id': firm.id, 'ledger_name': ledger_name})

    if request.user.is_authenticated():
        if request.method == 'POST':
            ledger = Ledger.objects.filter(firm_id=int(firm_id), name=request.POST['ledger'])[0]
            input_impress = Transaction()
            input_impress.ledger_id = ledger.id
            input_impress.amount = request.POST['amount']
            input_impress.mode = request.POST['mode']
            v_no = request.POST['voucher_no']
            ledgers = Ledger.objects.filter(firm_id=firm_id)
            data = check_voucher_no(v_no, firm_id)
            if data[0]:
                obj = Transaction.objects.filter(voucher__voucher_no=v_no,ledger__firm_id=firm_id)[0]
                return render(request, 'transaction/add_impress.html',
                              {'name': firm.name, 'year': firm.year, 'id': firm.id,
                                'failure': 'True', 'obj': obj,
                               'input_impress':input_impress,'v_no':v_no
                               })
            for ledger in ledgers:
                if ledger.name == request.POST['ledger']:
                    voucher_new = Voucher()
                    voucher_new.voucher_no = request.POST['voucher_no']
                    voucher_new.save()
                    impress = Transaction()
                    impress.ledger_id = ledger.pk
                    impress.amount = request.POST['amount']
                    impress.mode = request.POST['mode']
                    impress.description = request.POST['description']
                    impress.voucher_id = voucher_new.pk
                    impress.type = 'Credit'
                    impress.voucher_type = 'Impress'
                    impress.save()
                    cash = Transaction()
                    CASH = Ledger.objects.filter(firm_id=int(firm_id), name='Cash')[0]
                    cash.ledger_id = CASH.id
                    cash.voucher_type = 'Journal'
                    cash.description = impress.description
                    cash.amount = impress.amount
                    cash.mode = impress.mode
                    cash.type = 'Debit'
                    cash.save()
                    message = "Imprest Data has been saved !"
                    impresses = Transaction.objects.filter(ledger__firm_id=int(firm_id),voucher_type='Impress')
                    return render(request, 'transaction/impress_home.html', {'impresses':impresses,'message': message,'name':firm.name,'year':firm.year,'id':firm.id})

            return render(request, 'transaction/impress_home.html',{'name':firm.name,'year':firm.year,'id':firm.id})
        else:
            return render(request,'transaction/add_impress.html',{'name':firm.name,'year':firm.year,'id':firm.id})
    else:
        return redirect('/login')
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)
Ejemplo n.º 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'
Ejemplo n.º 6
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()
Ejemplo n.º 7
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
Ejemplo n.º 8
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')
Ejemplo n.º 9
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)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
def log_bal(request, data):
    transaction = Transaction(phone_no=data['phone'],
                              amount=data['amount'],
                              cid=data['cid'],
                              status='pending')
    transaction.save()

    return 'successful'
Ejemplo n.º 13
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)
Ejemplo n.º 14
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/')
Ejemplo n.º 15
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})
Ejemplo n.º 16
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)
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
def add_firm(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            print('INside POSt')
            name = request.POST['firm_name']
            year = request.POST['firm_year']
            password = request.POST['pass']
            password_1 = request.POST['pass_1']
            if password == password_1:
                firm = Firm()
                firm.name = name
                firm.year = year
                firm.password = password
                firm.save()
                print('Firm Data saved')
                ledger = Ledger()
                ledger.name = 'Cash'
                ledger.address = 'none'
                ledger.mobile_no = 'none'
                ledger.pan_no = 'none'
                ledger.type = 'Personal'
                ledger.firm_id = firm.id
                ledger.save()
                if request.POST['cash'] != "True":
                    amount = request.POST['balance']
                    type = request.POST['type']
                    entry = Transaction()
                    entry.ledger_id = ledger.id
                    entry.description = "opening balance entered"
                    if type == 'D':
                        entry.type = 'Debit'
                    else:
                        entry.type = 'Credit'
                    voucher = Voucher()
                    voucher.voucher_no = -1
                    voucher.save()
                    entry.voucher_id = voucher.id
                    entry.voucher_type = 'Opening'
                    entry.amount = amount
                    entry.save()
                    return redirect('/firm/firm_login')
                else:
                    print('no opening balance')
                return redirect('/firm/firm_login')
            else:
                return render(request, 'firm/add_firm.html',
                              {'message': 'Your passwords do not match !'})
        else:
            return render(request, 'firm/add_firm.html')
    else:
        return redirect('/login')
Ejemplo n.º 19
0
def amount2(request):
    user = Customer.objects.get(user=request.user)
    t = Transaction(previous_balance=Decimal(user.balance))
    amount = request.POST.get('deposit')
    t.amount = Decimal(amount)
    user.balance = user.get_balance(amount, 2)
    t.current_balance = Decimal(user.balance)
    t.user = request.user
    t.save()
    t.transaction_id = t.get_transaction_id()
    t.type = 'Deposit'
    t.save()
    user.save()
    return HttpResponseRedirect(reverse('customer:profile'))
Ejemplo n.º 20
0
def create_new_transaction(user, contact_person, contact_number,
                           shipment_datetime, material, rate):
    transaction = Transaction()
    transaction.transaction_id = get_new_transaction_id(user)
    transaction.booking_agent = user
    transaction.total_vehicle_requested = ''
    transaction.material = material
    transaction.contact_person = contact_person
    transaction.contact_number = contact_number
    transaction.transaction_managed_by = User.objects.get(username='******')
    transaction.shipment_datetime = parse_iso(shipment_datetime)
    transaction.expected_rate = rate
    transaction.save()
    return transaction
Ejemplo n.º 21
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'
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
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})
Ejemplo n.º 24
0
def amount(request):
    user = Customer.objects.get(user=request.user)
    t = Transaction(previous_balance=Decimal(user.balance))
    withdraw = request.POST.get('withdraw')
    t.amount = Decimal(withdraw)
    a = user.get_balance(withdraw, 1)
    if a == -1:
        messages.error(request, "No Balance!")
    else:
        user.balance = a
    t.current_balance = Decimal(user.balance)
    t.user = request.user
    t.save()
    t.transaction_id = t.get_transaction_id()
    t.type = 'Withdrawal'
    t.save()
    user.save()
    return HttpResponseRedirect(reverse('customer:profile'))
Ejemplo n.º 25
0
def read_condo_rental(input_path='Residential_rental.xlsx'):

    book = xlrd.open_workbook(input_path)
    sheet = book.sheet_by_index(0)

    list = []

    for row in range(2, sheet.nrows):
        name = sheet.cell(row, 0).value
        year = int(sheet.cell(row, 1).value)
        month = int(sheet.cell(row, 2).value)
        postal_code = sheet.cell(row, 3).value
        if postal_code == "nil" or postal_code == "":
            postal_code = None
        address = sheet.cell(row, 4).value
        area_sqm = sheet.cell(row, 5).value.replace(',', '')
        if area_sqm[0] == '>':
            area_sqm_min = area_sqm[1:]
            area_sqm_max = None
        else:
            area_sqm = area_sqm.split(' to ')
            area_sqm_min = float(area_sqm[0])
            area_sqm_max = float(area_sqm[1])
        try:
            room_count = int(sheet.cell(row, 6).value)
        except ValueError:
            room_count = None
        monthly_rent = float(sheet.cell(row, 7).value)

        transaction = Transaction(type='c',
                                  name=name,
                                  year=year,
                                  month=month,
                                  postal_code=postal_code,
                                  address=address,
                                  area_sqm_min=area_sqm_min,
                                  area_sqm_max=area_sqm_max,
                                  room_count=room_count,
                                  monthly_rent=monthly_rent)
        list.append(transaction)

    print len(list)
    return list
Ejemplo n.º 26
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)
Ejemplo n.º 27
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
Ejemplo n.º 28
0
    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)
Ejemplo n.º 29
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)
Ejemplo n.º 30
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)