Exemple #1
0
    def setUp(self):
        super(UpdateWithdrawAddressTestCase, self).setUp()

        PaymentMethod.objects.all().delete()

        method_data = {
            'bin': 426101,
            'fee': 0.0,
            'is_slow': 0,
            'name': 'Alpha Bank Visa'
        }
        payment_method = PaymentMethod(**method_data)
        payment_method.save()

        pref_data = {
            'user': self.user,
            'identifier': str(payment_method.bin),
            'comment': 'Just testing'
        }
        pref = PaymentPreference(**pref_data)
        pref.save()
        pref.currency.add(self.USD)
        pref.save()
        """Creates an order"""
        data = {
            'amount_cash': Decimal(30674.85),
            'amount_btc': Decimal(1.00),
            'currency': self.USD,
            'user': self.user,
            'admin_comment': 'test Order',
            'unique_reference': '12345',
            'payment_preference': pref
        }

        order = Order(**data)
        # TODO: patch and uncomment
        # order.full_clean()  # ensure is initially correct
        order.save()
        self.order = order

        pk = self.order.pk
        self.url = reverse('core.update_withdraw_address', kwargs={'pk': pk})

        self.addr_data = {
            'type': 'W',
            'name': '17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j',
            'address': '17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j',
        }
        self.addr = Address(**self.addr_data)
        self.addr.user = self.user
        self.addr.save()

        # The 'other' address for the Transaction
        user = User.objects.create_user(username='******')
        addr2 = Address(**self.addr_data)
        addr2.user = user
        addr2.save()
def process_data(request, data):
    # Process Employer
    try:
        employer = Employer.objects.get(name=data[0]['name'])
    except (Employer.DoesNotExist):
        empl_address = Address(street=data[0]['street'],
                               city=data[0]['city'],
                               state=data[0]['state'],
                               zip_code=data[0]['zip_code'],
                               address_type=data[0]['address_type'])
        empl_address.save()
        employer = Employer(name=data[0]['name'],
                            employer_address=empl_address)
        try:
            employer.full_clean()
            employer.save()
        except ValidationError as e:
            print(e, 'employer error')
    # Process Employee
    try:
        employee = EmployeeModel.objects.get(empl_ssn=data[1]['empl_ssn'])
    except (EmployeeModel.DoesNotExist):
        try:
            empl_address = Address.objects.get(street=data[1]['street'],
                                               zip_code=data[1]['zip_code'])
        except (Address.DoesNotExist):
            empl_address = Address(street=data[1]['street'],
                                   city=data[1]['city'],
                                   state=data[1]['state'],
                                   zip_code=data[1]['zip_code'],
                                   address_type=data[1]['address_type'])
            empl_address.save()
        try:
            employee = EmployeeModel(empl_full_name=data[1]['empl_full_name'],
                                     empl_hire_date=data[1]['empl_hire_date'],
                                     empl_dob=data[1]['empl_dob'],
                                     empl_ssn=data[1]['empl_ssn'],
                                     empl_gender=data[1]['empl_gender'],
                                     empl_address=empl_address,
                                     employer=employer,
                                     form_type=data[1]['form_type'])
            employee.full_clean()
            employee.save()
        except ValidationError as e:
            print(e, 'employee creation error')

    app_model = ApplicationModel(name=employee.form_type,
                                 submit_user=request.user,
                                 employee=employee)
    try:
        app_model.full_clean()
        app_model.save()
    except ValidationError as e:
        print(e, 'app model error')

    return employee
Exemple #3
0
    def test_can_set_as_paid_if_has_withdraw_address_internal(self):
        # Creates an withdraw address fro this user
        address = Address(user=self.user,
                          type='W',
                          address='17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j')
        address.save()

        payment_method = PaymentMethod(name='Internal Test', is_internal=True)
        payment_method.save()

        pref = PaymentPreference(payment_method=payment_method,
                                 user=self.order.user,
                                 identifier='InternalTestIdentifier')
        pref.save()

        payment = Payment(payment_preference=pref,
                          amount_cash=self.order.amount_cash,
                          order=self.order,
                          currency=self.RUB,
                          user=self.order.user)
        payment.save()
        # Creates an Transaction for the Order, using the user Address
        transaction = Transaction(order=self.order,
                                  address_to=address,
                                  address_from=address)
        transaction.save()

        # Set Order as Paid
        response = self.client.post(self.url, {'paid': 'true'})
        expected = {"frozen": True, "paid": True, "status": "OK"}
        self.assertJSONEqual(
            json.dumps(expected),
            str(response.content, encoding='utf8'),
        )
Exemple #4
0
def user_btc_adress(request):
    btc_address = request.POST.get('btcAddress')
    user = request.user
    validate_bc(str(btc_address))
    address = Address(address=btc_address, user=user)
    address.save()
    return JsonResponse({'status': 'OK'})
Exemple #5
0
def update_stripe_customer_info(request: HttpRequest,
                                team_id: str) -> HttpResponse:
    """
    Endpoint to allow users to update Stripe customer info.
    """
    account = get_account_or_404(team_id=team_id, user=request.user)
    payload = UpdateBillingInfoModel.parse_raw(request.body)
    if payload.limitBillingAccessToOwners is not None:
        if not request.user.is_admin(account):
            raise PermissionDenied
        account.limit_billing_access_to_owners = payload.limitBillingAccessToOwners
        account.save()

    if (payload.email is not None or payload.name is not None
            or payload.address is not None):
        if not request.user.can_edit_subscription(account):
            raise PermissionDenied
        account.update_billing_info(
            email=payload.email,
            name=payload.name,
            address=(Address(
                line1=payload.address.line1,
                city=payload.address.city,
                country=payload.address.country,
                line2=payload.address.line2,
                postal_code=payload.address.postalCode,
                state=payload.address.state,
            ) if payload.address is not None else None),
        )
    return HttpResponse(status=204)
Exemple #6
0
    def setUp(self):
        super(WalletBaseTestCase, self).setUp()
        # look at:
        # nexchange/tests/fixtures/transaction_history.xml self.order_data
        # matches first transaction from the XML file
        okpay_pref = PaymentPreference.objects.filter(
            user__is_staff=True,
            payment_method__name__icontains='okpay').first()

        payeer_pref = PaymentPreference.objects.filter(
            user__is_staff=True,
            payment_method__name__icontains='payeer').first()

        mock = get_ok_pay_mock()
        self.okpay_order_data = {
            'amount_quote': Decimal(split_ok_pay_mock(mock, 'Net')),
            'amount_base': Decimal(0.1),
            'pair': self.BTCEUR,
            'user': self.user,
            'admin_comment': 'tests Order',
            'unique_reference': split_ok_pay_mock(mock, 'Comment'),
            'payment_preference': okpay_pref,
        }
        self.payeer_order_data = deepcopy(self.okpay_order_data)
        self.payeer_order_data['payment_preference'] = payeer_pref

        self.okpay_order_data_address = deepcopy(self.okpay_order_data)
        addr = Address(address='A555B', user=self.user)
        addr.save()
        self.okpay_order_data_address['withdraw_address'] = addr

        self.payeer_order_data_address = deepcopy(
            self.okpay_order_data_address)
        self.payeer_order_data_address['payment_preference'] = payeer_pref
Exemple #7
0
 def setUp(self):
     self.professional = Professional.objects.create(
         user=User.objects.create_user(
             email='*****@*****.**',
             password='******',
             is_active=True,
             cpf="396.852.650-38",
         ))
     self.professional.user.save()
     self.professional.save()
     self.user = User.objects.create_user(
         email='*****@*****.**',
         password='******',
         is_active=True,
         born=(now() - timedelta(days=10000)).date(),
         full_name='Nerso da Silva',
         cellphone='988883333',
         cpf="529.982.247-25",
         cellphone_ddd='43',
     )
     address = Address(
         user=self.user,
         street='Rua Tal',
         street_number='45',
         zipcode='45666-333',
         state='MG',
         city='Notredame',
         neighborhood='Gran',
         complementary='Fundos',
     )
     address.save()
     self.user.save()
     self.proposal = Proposal(client=self.user,
                              professional=self.professional,
                              city='Curitiba',
                              state='PR',
                              professional_type='AE',
                              service_type='AC',
                              start_datetime=TODAY + timedelta(days=1),
                              end_datetime=TODAY + timedelta(days=3),
                              value=300.00,
                              description='Lorem Ipsum dolores')
     self.proposal.save()
     self.proposal.accept()
     self.user.create_customer()
     self.user.create_card({
         "card_expiration_date": "1122",
         "card_number": "4018720572598048",
         "card_cvv": "123",
         "card_holder_name": "Cersei Lannister"
     })
     self.professional.create_recipient(
         **{
             'agency': '0932',
             'agency_dv': '5',
             'bank_code': '341',
             'account': '58054',
             'account_dv': '1',
             'legal_name': 'HOUSE TARGARYEN'
         })
Exemple #8
0
    def setUp(self):
        super(PaymentReleaseTestCase, self).setUp()
        self.method_data = {"is_internal": 1, 'name': 'Robokassa'}

        amount_cash = Decimal(30000.00)

        self.payment_method = PaymentMethod(name='ROBO')
        self.payment_method.save()

        self.addr_data = {
            'type': 'W',
            'name': '17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j',
            'address': '17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j',
        }

        self.addr = Address(**self.addr_data)
        self.addr.user = self.user
        self.addr.save()

        pref_data = {
            'user': self.user,
            'comment': 'Just testing',
            'payment_method': self.payment_method
        }

        pref = PaymentPreference(**pref_data)
        pref.save('internal')

        self.data = {
            'amount_cash': amount_cash,
            'amount_btc': Decimal(1.00),
            'currency': self.RUB,
            'user': self.user,
            'admin_comment': 'test Order',
            'unique_reference': '12345',
            'payment_preference': pref,
            'is_paid': True
        }

        self.order = Order(**self.data)
        self.order.save()

        self.pay_data = {
            'amount_cash': self.order.amount_cash,
            'currency': self.RUB,
            'user': self.user,
            'payment_preference': pref,
        }

        self.payment = Payment(**self.pay_data)
        self.payment.save()

        tx_id_ = '76aa6bdc27e0bb718806c93db66525436' \
                 'fa621766b52bad831942dee8b618678'

        self.transaction = Transaction(tx_id=tx_id_,
                                       order=self.order,
                                       address_to=self.addr)
        self.transaction.save()
Exemple #9
0
 def test_bittrex_release_with_objects(self, withdraw):
     client = BittrexApiClient()
     curr_code = 'XVG'
     curr = Currency.objects.get(code=curr_code)
     address_address = '123'
     address = Address(address=address_address,
                       currency=curr,
                       type=Address.WITHDRAW)
     amount = 123
     client.release_coins(curr, address, amount)
     withdraw.assert_called_with(curr_code, amount, address_address)
Exemple #10
0
 def _create_withdraw_adress(self, currency, address):
     addr_data = {
         'type': 'W',
         'name': address,
         'address': address,
         'currency': currency
     }
     addr = Address(**addr_data)
     addr.user = self.user
     addr.save()
     return addr
Exemple #11
0
 def test_release_call_decrypt(self, get_pass, get_api, call_api, unlock,
                               lock):
     get_pass.return_value = 'randomPass'
     get_api.return_value = mock.MagicMock()
     api = ScryptRpcApiClient()
     curr = Currency(code='BTC', wallet='rpc5')
     addr = Address()
     amount = 42
     api.release_coins(curr, addr, amount)
     self.assertEqual(call_api.call_count, 1)
     self.assertEqual(lock.call_count, 1)
     get_api.assert_called_with('rpc5')
Exemple #12
0
 def setUp(self):
     super(BlockchainTestCase, self).setUp()
     self.wallet_address = '198aMn6ZYAczwrE5NvNTUMyJ5qkfy4g3Hi'
     self.address = Address(
         name='test address',
         address=self.wallet_address,
         currency=self.BTC,
         user=self.user
     )
     self.url = 'http://btc.blockr.io/api/v1/address/txs/{}'.format(
         self.wallet_address
     )
Exemple #13
0
def generate_addresses(request, times):
    for i in range(0, times):
        a = Address()
        idx = random.randint(0, 1)
        a.address_type = ['B', 'S'][idx]
        a.first_name = random_text('t', 15)
        a.last_name = random_text('t', 15)
        a.address = random_text('t', 50)
        a.zipcode = random_text('n', 5)
        a.country = random_text('t', 10)
        a.city = random_text('t', 10)
        a.save()
    return HttpResponse(f'{times} Addresses generated !')
Exemple #14
0
 def update(self, instance, validated_data):
     refund_address = validated_data.pop('refund_address')
     addr_list = Address.objects.filter(address=refund_address['address'])
     if not addr_list:
         address = Address(**refund_address)
         address.type = Address.WITHDRAW
         address.currency = instance.pair.quote
         address.save()
     else:
         address = addr_list[0]
     instance.refund_address = address
     instance.save()
     return instance
Exemple #15
0
    def create(self, validated_data):
        for field in READABLE_FIELDS:
            validated_data.pop(field, None)
        withdraw_address = validated_data.pop('withdraw_address')
        refund_address = validated_data.pop('refund_address')
        validated_data.pop('pair')
        withdraw_addr_list = Address.objects.filter(
            address=withdraw_address['address'])
        order = LimitOrder(pair=self.pair,
                           order_book=self.order_book,
                           **validated_data)
        if not withdraw_addr_list:
            w_address = Address(**withdraw_address)
            w_address.type = Address.WITHDRAW
            w_address.currency = order.withdraw_currency
            w_address.save()
        else:
            w_address = withdraw_addr_list[0]

        order.withdraw_address = w_address
        refund_addr_list = Address.objects.filter(
            address=refund_address['address'])
        if not refund_addr_list:
            r_address = Address(**refund_address)
            r_address.type = Address.REFUND
            r_address.currency = order.refund_currency
            r_address.save()
        else:
            r_address = refund_addr_list[0]
        order.refund_address = r_address
        try:
            order.save()
            # get post_save stuff in sync
            order.refresh_from_db()
            return order
        except ValidationError as e:
            raise RestValidationError({'non_field_errors': [e.message]})
Exemple #16
0
 def test_kraken_release_with_objects(self, q_private):
     client = KrakenApiClient()
     curr_code = 'DOGE'
     curr = Currency.objects.get(code=curr_code)
     address_address = '123'
     address = Address(address=address_address,
                       currency=curr,
                       type=Address.WITHDRAW)
     amount = 123
     client.release_coins(curr, address, amount)
     q_private.assert_called_with('Withdraw', {
         'amount': str(amount),
         'asset': 'XXDG',
         'key': address_address
     })
Exemple #17
0
def create_withdraw_address(request, order_pk):
    error_message = 'Error creating address: %s'
    order = Order.objects.get(pk=order_pk)
    if not order.user.profile.is_verified and not order.exchange:
        pm = order.payment_preference.payment_method
        if pm.required_verification_buy or order.user.profile.anonymous_login:
            resp = {
                'status':
                'ERR',
                'msg':
                'You need to be a verified user to set withdrawal '
                'address for order with payment method \'{}\''
                ''.format(pm.name)
            }
            return JsonResponse(resp, safe=False)

    address = request.POST.get('value')
    addr = Address()
    addr.type = Address.WITHDRAW
    addr.user = request.user
    addr.address = address
    if order.order_type == Order.BUY:
        currency = order.pair.base
    else:
        currency = order.pair.quote
    addr.currency = currency

    try:
        if currency.code == 'BTC':
            validate_btc(addr.address)
        elif currency.code == 'LTC':
            validate_ltc(addr.address)
        elif currency.code == 'ETH':
            validate_eth(addr.address)
        else:
            validate_address(addr.address)
        addr.save()
        resp = {'status': 'OK', 'pk': addr.pk, 'target': addr.currency.code}

    except ValidationError:
        resp = {'status': 'ERR', 'msg': 'The supplied address is invalid.'}

    except Exception as e:
        msg = error_message % (e)
        resp = {'status': 'ERR', 'msg': msg}

    return JsonResponse(resp, safe=False)
Exemple #18
0
    def create(self, validated_data):
        for field in READABLE_FIELDS:
            validated_data.pop(field, None)
        withdraw_address = validated_data.pop('withdraw_address')
        payment_id = withdraw_address.pop('payment_id', None)
        destination_tag = withdraw_address.pop('destination_tag', None)
        validated_data.pop('pair')
        # Just making sure
        addr_list = Address.objects.filter(address=withdraw_address['address'])
        order = Order(pair=self.pair, **validated_data)
        if payment_id:
            order.payment_id = payment_id
        if destination_tag:
            order.destination_tag = destination_tag
        if not addr_list:
            address = Address(**withdraw_address)
            address.type = Address.WITHDRAW
            address.currency = order.pair.base
            address.save()
        else:
            address = addr_list[0]

        order.withdraw_address = address
        try:
            order.save()
            # get post_save stuff in sync
            order.refresh_from_db()
            self.fields['deposit_address'] = NestedReadOnlyAddressSerializer(
                many=False,
                read_only=True,
                additional_params={
                    'destination_tag': order.quote_destination_tag,
                    'payment_id': order.quote_payment_id
                })
            self.fields['withdraw_address'] = NestedAddressSerializer(
                many=False,
                read_only=False,
                additional_params={
                    'destination_tag': order.base_destination_tag,
                    'payment_id': order.base_payment_id
                })
            return order
        except ValidationError as e:
            raise RestValidationError({'non_field_errors': [e.message]})
Exemple #19
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            name = form.cleaned_data.get('name')
            phone = form.cleaned_data.get('phone')

            if is_valid_form([email, name, phone]):
                shipping_address = Address(
                    email=email,
                    name=name,
                    phone=phone,
                )
                shipping_address.save()
                BasketItem.objects.all()
                return redirect("core:thank-you")
        else:
            messages.info(self.request, "All fields are required.")
        return redirect("core:checkout")
Exemple #20
0
    def test_can_set_as_paid_if_has_withdraw_address(self):
        # Creates an withdraw address fro this user
        address = Address(user=self.user,
                          type='W',
                          address='17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j')
        address.save()

        # Creates an Transaction for the Order, using the user Address
        transaction = Transaction(order=self.order,
                                  address_to=address,
                                  address_from=address)
        transaction.save()

        # Set Order as Paid
        response = self.client.post(self.url, {'paid': 'true'})
        expected = {"frozen": None, "paid": True, "status": "OK"}
        self.assertJSONEqual(
            json.dumps(expected),
            str(response.content, encoding='utf8'),
        )
Exemple #21
0
def update_stripe_customer_info(request: HttpRequest,
                                team_id: str) -> HttpResponse:
    """
    Endpoint to allow users to update Stripe customer info.
    """
    account = get_account_or_404(team_id=team_id, user=request.user)
    payload = UpdateBillingInfoModel.parse_raw(request.body)
    account.update_billing_info(
        email=payload.email,
        name=payload.name,
        address=(Address(
            line1=payload.address.line1,
            city=payload.address.city,
            country=payload.address.country,
            line2=payload.address.line2,
            postal_code=payload.address.postalCode,
            state=payload.address.state,
        ) if payload.address is not None else None),
    )
    return HttpResponse(status=204)
Exemple #22
0
 def setUp(self):
     super(RetryReleaseTestCase, self).setUp()
     self.address = Address(
         type=Address.WITHDRAW,
         address='0x993cE7372Ed0621ddD4593ac3433E678236A496D')
     self.address.save()
     self.ETH = Currency.objects.get(code='ETH')
     self.client = UpholdApiClient()
     self._create_order()
     self.order.status = Order.PRE_RELEASE
     self.order.withdraw_address = self.address
     self.order.save()
     self.tx_data = {
         'currency': self.order.pair.base,
         'amount': self.order.amount_base,
         'order': self.order,
         'address_to': self.order.withdraw_address,
         'type': Transaction.WITHDRAW
     }
     self.retry_release = RetryOrderRelease(api=self.client)
Exemple #23
0
    def post(self, request):
        data = request.data
        fio = data["name"].split()
        if len(fio) == 3:
            fio = {
                "last_name": fio[0],
                "first_name": fio[1],
                "father_name": fio[2]
            }
        elif len(fio) == 2:
            fio = {
                "last_name": fio[0],
                "first_name": fio[1],
                "father_name": ""
            }
        elif len(fio) == 1:
            fio = {
                "last_name": "",
                "first_name": fio[0],
                "father_name": ""
            }
        else:
            fio = {
                "last_name": "Иванов",
                "first_name": "Иван",
                "father_name": "Иванович"
            }

        user = User(**fio)
        user.save()

        Address(name=data["address"], user=user).save()

        for phone in data["phones"]:
            Phone(
                user=user,
                number=phone["number"],
                type=get_type_by_type_name(phone["type"])
            ).save()

        return Response(user.id, status=status.HTTP_201_CREATED)
Exemple #24
0
    def setUp(self):
        super(BaseOrderReleaseTestCase, self).setUp()
        enable_all_pairs()
        currencies = Currency.objects.filter(is_crypto=False)
        for curr in currencies:
            curr.maximal_amount = 50000000
            curr.minimal_amount = 0.1
            curr.save()
        self.payments = []
        self.orders = []
        self.addr = Address(address='12345', user=self.user)
        self.addr.save()
        self.our_pref = PaymentPreference.objects.first()
        self.order_data = {
            'amount_quote': Decimal(30674.85),
            'amount_base': Decimal(1.00),
            'user': self.user,
            'admin_comment': 'tests Order',
            'unique_reference': '123456',
            'payment_preference': self.our_pref,
            'withdraw_address': self.addr,
            'pair': self.BTCRUB,
        }

        self.pref, created = PaymentPreference.objects.get_or_create(
            payment_method=self.our_pref.payment_method,
            user=self.user,
            identifier='1234567',
        )

        self.pref.currency.add(self.BTCRUB.quote)
        self.pref.save()

        self.base_payment_data = {
            'user': self.user,
            'currency': self.BTCRUB.quote,
            'payment_preference': self.pref,
            'amount_cash': self.order_data['amount_quote'],
            'is_success': True
        }
Exemple #25
0
def signupLevel1(request):
    activationKey = request.data.get('activationKey')
    verifyMobileNumber = request.data.get('verifyMobileNumber')
    profile = get_object_or_404(Profile, activationKey=activationKey)
    profile.user.set_password(request.data.get('password'))
    profile.user.is_active = True
    profile.user.save()
    profile.dob = request.data.get('dob')
    address = Address()
    address.country = request.data.get('country')
    address.region = request.data.get('region')
    address.city = request.data.get('city')
    address.street = request.data.get('address')
    address.zipCode = request.data.get('zipcode')
    address.save()
    profile.defaultAddress = address
    profile.mobile = request.data.get('mobile')
    if request.data.get('ssn') and len(request.data.get('ssn')) > 0:
        profile.ssn = request.data.get('ssn')
    profile.termsAgreement = request.data.get('agreement')
    profile.setVerificationCode()
    profile.save()
    try:
        if verifyMobileNumber:
            messageSend = sendVerificationCodeSMS(request,
                                                  profile.verificationCode,
                                                  profile.mobile)
        else:
            profile.setActivationKey()
            profile.mobileVerified = True
            profile.save()
        return Response({'success': True})
    except Exception as e:
        return Response({
            'success': False,
            'error': {
                'code': 'no.sms.sent',
                'msg': e.message
            }
        })
Exemple #26
0
    def create_user_wallet(self, user, currency):
        one_card_currencies = ['XMR', 'XRP']
        unassigned_cards = AddressReserve.objects.filter(currency=currency,
                                                         user=None,
                                                         disabled=False)
        if currency.code in one_card_currencies:
            unassigned_cards = AddressReserve.objects.filter(currency=currency,
                                                             disabled=False)

        if len(unassigned_cards) == 0 \
                and currency.code not in one_card_currencies:
            self.logger.warning('instance {} has no reserve cards available'
                                ' for {} calling renew_cards_reserve()'.format(
                                    user, currency))

            self.renew_cards_reserve(
                expected_reserve=settings.EMERGENCY_CARDS_RESERVE_COUNT)
            unassigned_cards = AddressReserve.objects.filter(currency=currency,
                                                             user=None,
                                                             disabled=False)

        if unassigned_cards:
            # FIFO
            card = unassigned_cards.earliest('id')
            card.user = user
            try:
                address = Address.objects.get(address=card.address)
            except Address.DoesNotExist:
                address = Address(address=card.address,
                                  user=card.user,
                                  currency=currency,
                                  type=Address.DEPOSIT,
                                  reserve=card)
            address.save()
            card.save()
            return card, address
        else:
            self.logger.error(
                'instance {} has no cards available'.format(currency))
        return None, None
Exemple #27
0
def create_withdraw_address(request):
    error_message = 'Error creating address: %s'

    address = request.POST.get('value')

    addr = Address()
    addr.type = Address.WITHDRAW
    addr.user = request.user
    addr.address = address

    try:
        validate_bc(addr.address)
        addr.save()
        resp = {'status': 'OK', 'pk': addr.pk}

    except ValidationError:
        resp = {'status': 'ERR', 'msg': 'The supplied address is invalid.'}

    except Exception as e:
        msg = error_message % (e)
        resp = {'status': 'ERR', 'msg': msg}

    return JsonResponse(resp, safe=False)
def basket_create(request):
    if request.POST.get("address"):
        address = Address.objects.get(id=request.POST.get("address"))
    else:
        address = Address(user=request.user,
                          name=request.POST.get("name"),
                          city=request.POST.get("city"),
                          street=request.POST.get("street"),
                          home=request.POST.get("home"),
                          flat=request.POST.get("flat"))
        address.save()

    order_ = Order.objects.get(user=request.user, status__base_status__id=1)
    order_.address = address
    order_.payment_method = PaymentMethod.objects.get(
        id=request.POST.get("payment_method"))
    status = Status(base_status=BaseStatus.objects.get(id=2),
                    datetime=datetime.now())
    status.save()
    order_.status.add(status)
    order_.status.remove(order_.status.all()[0])
    order_.save()

    return HttpResponseRedirect("/profile/")
Exemple #29
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():

                use_default_shipping = form.cleaned_data.get(
                    'use_default_shipping')
                if use_default_shipping:
                    print("Using the defualt shipping address")
                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type='S',
                                                        default=True)
                    if address_qs.exists():
                        shipping_address = address_qs[0]
                        order.shipping_address = shipping_address
                        order.save()
                    else:
                        messages.info(self.request,
                                      "No default shipping address available")
                        return redirect('core:checkout')
                else:
                    print("User is entering a new shipping address")
                    shipping_address1 = form.cleaned_data.get(
                        'shipping_address')
                    shipping_address2 = form.cleaned_data.get(
                        'shipping_address2')
                    shipping_country = form.cleaned_data.get(
                        'shipping_country')
                    shipping_zip = form.cleaned_data.get('shipping_zip')

                    if is_valid_form(
                        [shipping_address1, shipping_country, shipping_zip]):
                        shipping_address = Address(
                            user=self.request.user,
                            street_address=shipping_address1,
                            apartment_address=shipping_address2,
                            country=shipping_country,
                            zip=shipping_zip,
                            address_type='S')
                        shipping_address.save()

                        order.shipping_address = shipping_address
                        order.save()

                        set_default_shipping = form.cleaned_data.get(
                            'set_default_shipping')
                        if set_default_shipping:
                            shipping_address.default = True
                            shipping_address.save()

                    else:
                        messages.info(
                            self.request,
                            "Please fill in the required shipping address fields"
                        )

                use_default_billing = form.cleaned_data.get(
                    'use_default_billing')
                same_billing_address = form.cleaned_data.get(
                    'same_billing_address')

                if same_billing_address:
                    billing_address = shipping_address
                    billing_address.pk = None
                    billing_address.save()
                    billing_address.address_type = 'B'
                    billing_address.save()
                    order.billing_address = billing_address
                    order.save()

                elif use_default_billing:
                    print("Using the defualt billing address")
                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type='B',
                                                        default=True)
                    if address_qs.exists():
                        billing_address = address_qs[0]
                        order.billing_address = billing_address
                        order.save()
                    else:
                        messages.info(self.request,
                                      "No default billing address available")
                        return redirect('core:checkout')
                else:
                    print("User is entering a new billing address")
                    billing_address1 = form.cleaned_data.get('billing_address')
                    billing_address2 = form.cleaned_data.get(
                        'billing_address2')
                    billing_country = form.cleaned_data.get('billing_country')
                    billing_zip = form.cleaned_data.get('billing_zip')

                    if is_valid_form(
                        [billing_address1, billing_country, billing_zip]):
                        billing_address = Address(
                            user=self.request.user,
                            street_address=billing_address1,
                            apartment_address=billing_address2,
                            country=billing_country,
                            zip=billing_zip,
                            address_type='B')
                        billing_address.save()

                        order.billing_address = billing_address
                        order.save()

                        set_default_billing = form.cleaned_data.get(
                            'set_default_billing')
                        if set_default_billing:
                            billing_address.default = True
                            billing_address.save()

                    else:
                        messages.info(
                            self.request,
                            "Please fill in the required billing address fields"
                        )

                payment_option = form.cleaned_data.get('payment_option')

                if payment_option == 'S':
                    return redirect('core:payment', payment_option='stripe')
                elif payment_option == 'P':
                    return redirect('core:payment', payment_option='paypal')
                else:
                    messages.warning(self.request,
                                     "Invalid payment option selected")
                    return redirect('core:checkout')
        except ObjectDoesNotExist:
            messages.warning(self.request, "You do not have an active order")
            return redirect("core:order-summary")
Exemple #30
0
 def setUp(self):
     self.obj = Address(street_address="800 N LBJ Drive",
                        apartment_address="215",
                        country="US",
                        zip="78666",
                        address_type="S")