def test_no_transaction_settle_with_only_related_proforma(self):
        proforma = ProformaFactory.create(related_document=None)

        customer = proforma.customer
        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=True,
        )

        proforma.issue()

        transaction = proforma.transactions[0]
        # here transaction.proforma is the same object as the proforma from the
        # DB due to the way transition callbacks and saves are called

        transaction.settle()
        transaction.save()

        self.assertEqual(proforma.state, proforma.STATES.PAID)

        invoice = proforma.related_document
        self.assertEqual(invoice.state, invoice.STATES.PAID)

        self.assertEqual(list(proforma.transactions),
                         list(invoice.transactions))

        self.assertEqual(len(proforma.transactions), 1)
Esempio n. 2
0
    def test_get_listing(self):
        PaymentMethodFactory.create(customer=CustomerFactory.create())
        payment_method = self.create_payment_method(customer=self.customer)

        url = reverse('payment-method-list', kwargs={
            'customer_pk': self.customer.pk
        })

        self.assert_get_data(url, [payment_method])
Esempio n. 3
0
    def test_get_detail(self):
        PaymentMethodFactory.create(customer=CustomerFactory.create())
        payment_method = self.create_payment_method(customer=self.customer)

        url = reverse('payment-method-detail', kwargs={
            'customer_pk': self.customer.pk,
            'payment_method_id': payment_method.pk
        })

        self.assert_get_data(url, payment_method)
Esempio n. 4
0
    def test_patch_transaction_with_initial_status(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor='someprocessor'
        )
        transaction = TransactionFactory.create(payment_method=payment_method)

        url = reverse('transaction-detail', args=[transaction.customer.pk,
                                                  transaction.uuid])

        valid_until = timezone.now()
        currency_rate_date = timezone.now().date()

        data = {
            'valid_until': valid_until,
            'currency': 'RON',
            'currency_rate_date': currency_rate_date,
            'amount': 200
        }

        response = self.client.patch(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        transaction.refresh_from_db()
        self.assertEqual(transaction.valid_until, valid_until)
        self.assertEqual(transaction.currency, 'RON')
        self.assertEqual(transaction.currency_rate_date, currency_rate_date)
        self.assertEqual(transaction.amount, 200)
Esempio n. 5
0
    def test_patch_transaction_documents(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor='someprocessor'
        )
        transaction = TransactionFactory.create(payment_method=payment_method)
        proforma = ProformaFactory.create()
        invoice = InvoiceFactory.create(proforma=proforma)
        proforma.invoice = invoice
        proforma.save()

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        url = reverse('transaction-detail', args=[transaction.customer.pk,
                                                  transaction.uuid])

        data = {
            'proforma': proforma_url,
            'invoice': invoice_url
        }

        response = self.client.patch(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        self.assertEqual(response.data, {
            'proforma': [u'This field may not be modified.'],
            'invoice': [u'This field may not be modified.']
        })
    def test_transaction_filtering(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            verified=True
        )

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method
        )

        filtered_transactions = [
            transactions[0], transactions[2], transactions[4]
        ]

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            transactions_arg = [
                str(transaction.pk) for transaction in filtered_transactions
            ]
            call_command('execute_transactions',
                         '--transactions=%s' % ','.join(transactions_arg))

            for transaction in filtered_transactions:
                self.assertIn(call(transaction), mock_execute.call_args_list)

            self.assertEqual(mock_execute.call_count, len(filtered_transactions))
    def test_encoding(self):
        payment_method = PaymentMethodFactory.create()

        factory = APIRequestFactory()
        url = reverse('payment-method-detail',
                      kwargs={'payment_method_id': payment_method.pk,
                              'customer_pk': payment_method.customer.pk})
        request = factory.get(url, format='json')

        serializer = PaymentMethodSerializer(payment_method, context={
            'request': request
        })

        expected_data = OrderedDict([
            ('url', 'http://testserver/customers/{}/payment_methods/{}/'.format(payment_method.customer.pk,
                                                                                payment_method.pk)),
            ('transactions', None),
            ('customer', 'http://testserver/customers/{}/'.format(payment_method.customer.pk)),
            ('payment_processor', 'http://testserver/payment_processors/Manual/'),
            ('added_at', payment_method.added_at),
            ('verified_at', None),
            ('state', 'uninitialized')
        ])

        json = JSONRenderer().render(serializer.data)
        self.assertEqual(json, JSONRenderer().render(expected_data))
Esempio n. 8
0
    def test_get_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        transaction = TransactionFactory.create(payment_method=payment_method)
        invoice = transaction.invoice
        proforma = transaction.proforma
        provider = invoice.provider

        expected = OrderedDict([
            ('id', unicode(transaction.uuid)),
            ('url', reverse('transaction-detail',
                            kwargs={'customer_pk': customer.id, 'transaction_uuid': transaction.uuid})),
            ('customer', reverse('customer-detail', args=[customer.pk])),
            ('provider', reverse('provider-detail', args=[provider.pk])),
            ('amount', unicode(Decimal('0.00') + transaction.amount)),
            ('currency', unicode(transaction.currency)),
            ('currency_rate_date', None),
            ('state', unicode(transaction.state)),
            ('proforma', reverse('proforma-detail', args=[proforma.pk])),
            ('invoice', reverse('invoice-detail', args=[invoice.pk])),
            ('can_be_consumed', transaction.can_be_consumed),
            ('payment_method', reverse('payment-method-detail', kwargs={'customer_pk': customer.id,
                                                                        'payment_method_id': payment_method.id})),
            ('pay_url', reverse('pay-transaction', kwargs={'transaction_uuid': transaction.uuid})),
            ('valid_until', None)
        ])

        url = reverse('transaction-detail',
                      kwargs={'customer_pk': customer.pk,
                              'transaction_uuid': transaction.uuid})
        response = self.client.get(url, format='json')

        self.assertEqual(response.data, dict(expected))
Esempio n. 9
0
    def test_add_transaction_with_documents_for_a_different_customer(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        proforma = ProformaFactory.create()
        proforma.state = proforma.STATES.ISSUED
        proforma.create_invoice()
        proforma.refresh_from_db()
        invoice = proforma.invoice

        valid_until = datetime.now()
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk, 'payment_method_id': payment_method.pk})
        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method': reverse('payment-method-detail', kwargs={'customer_pk': customer.pk,
                                                                       'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'amount': 200.0,
            'invoice': invoice_url,
            'proforma': proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [u"Customer doesn't match with the one in documents."]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Esempio n. 10
0
    def test_add_transaction_with_unrelated_documents(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        invoice = InvoiceFactory.create(customer=customer)
        proforma = ProformaFactory.create(customer=customer)
        valid_until = datetime.now()
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk, 'payment_method_id': payment_method.pk})
        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method': reverse('payment-method-detail', kwargs={'customer_pk': customer.pk,
                                                                       'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'amount': 200.0,
            'invoice': invoice_url,
            'proforma': proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [u'Invoice and proforma are not related.']
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    def test_fetch_transaction_status_transactions_filtering(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor
        )

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method, state=Transaction.States.Pending
        )

        filtered_transactions = [
            transactions[0], transactions[2], transactions[4]
        ]

        mock_fetch_status = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            transactions_arg = [
                str(transaction.pk) for transaction in filtered_transactions
            ]
            call_command('fetch_transactions_status',
                         '--transactions=%s' % ','.join(transactions_arg))

            for transaction in filtered_transactions:
                self.assertIn(call(transaction),
                              mock_fetch_status.call_args_list)

            self.assertEqual(mock_fetch_status.call_count,
                             len(filtered_transactions))
Esempio n. 12
0
    def test_documents_list_case_1(self):
        """
            One proforma, one invoice, without related documents
        """
        proforma = ProformaFactory.create()
        invoice_entries = DocumentEntryFactory.create_batch(3)
        invoice = InvoiceFactory.create(invoice_entries=invoice_entries)
        invoice.issue()
        payment_method = PaymentMethodFactory.create(customer=invoice.customer)
        transaction = TransactionFactory.create(payment_method=payment_method,
                                                invoice=invoice)

        url = reverse('document-list')

        with patch('silver.utils.payments._get_jwt_token',
                   new=self._jwt_token):
            response = self.client.get(url)

        # ^ there's a bug where specifying format='json' doesn't work
        response_data = response.data

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response_data), 2)

        self.assertIn(self._get_expected_data(invoice, [transaction]),
                      response_data)

        self.assertIn(self._get_expected_data(proforma), response_data)
    def test_transaction_creation_for_issued_documents(self):
        """
            The happy case.
        """
        invoice = InvoiceFactory.create()
        customer = invoice.customer

        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=True,
        )

        invoice.issue()

        transactions = Transaction.objects.filter(
            invoice=invoice, proforma=invoice.related_document
        )
        self.assertEqual(len(transactions), 1)
    def test_no_transaction_creation_at_proforma_pay(self):
        proforma = ProformaFactory.create(related_document=None)

        customer = proforma.customer
        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=True,
        )

        proforma.issue()
        proforma.pay()

        invoice = proforma.related_document

        self.assertEqual(len(Transaction.objects.filter(proforma=proforma)), 1)

        transaction = Transaction.objects.filter(proforma=proforma)[0]
        self.assertEqual(transaction.invoice, invoice)
    def test_no_transaction_creation_for_issued_documents_case2(self):
        """
            The payment method is not usable
        """
        invoice = InvoiceFactory.create()
        customer = invoice.customer
        PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False
        )

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor, execute_transaction=mock_execute):
            invoice.issue()

            transactions = Transaction.objects.filter(
                invoice=invoice, proforma=invoice.related_document
            )
            self.assertEqual(len(transactions), 0)
    def test_create_transactions_on_verified_payment_method_creation(self):
        customer = CustomerFactory.create()

        lone_invoice = InvoiceFactory.create(
            transaction_currency='USD',
            transaction_xe_rate=Decimal('1.0'),
            state=Invoice.STATES.ISSUED,
            customer=customer
        )

        lone_proforma = ProformaFactory.create(
            transaction_currency='USD',
            transaction_xe_rate=Decimal('1.0'),
            state=Proforma.STATES.ISSUED,
            customer=customer
        )

        paired_proforma = ProformaFactory.create(
            transaction_currency='USD',
            transaction_xe_rate=Decimal('1.0'),
            state=Proforma.STATES.ISSUED,
            issue_date=timezone.now().date(),
            customer=customer
        )
        paired_invoice = paired_proforma.create_invoice()

        PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=customer,
            canceled=False,
            verified=True
        )

        self.assertEqual(lone_invoice.transactions.count(), 1)

        self.assertEqual(lone_proforma.transactions.count(), 1)

        self.assertEqual(list(paired_invoice.transactions),
                         list(paired_proforma.transactions))

        self.assertEqual(paired_invoice.transactions.count(), 1)
    def test_skip_transaction_with_unverified_payment_method(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            verified=False
        )

        TransactionFactory.create(payment_method=payment_method)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')

            self.assertEqual(mock_execute.call_count, 0)
Esempio n. 18
0
    def test_create_one_without_required_fields(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        valid_until = datetime.now().replace(microsecond=0)

        data = {'valid_until': valid_until}

        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.id,
                          'payment_method_id': payment_method.id
                      })

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.data['payment_method'],
                         ['This field is required.'])
Esempio n. 19
0
    def test_create_transactions_on_payment_method_verify(self):
        customer = CustomerFactory.create()

        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=customer,
            canceled=False,
            verified=False
        )

        lone_invoice = InvoiceFactory.create(
            transaction_currency='USD',
            transaction_xe_rate=Decimal('1.0'),
            state=Invoice.STATES.ISSUED,
            customer=customer
        )

        lone_proforma = ProformaFactory.create(
            transaction_currency='USD',
            transaction_xe_rate=Decimal('1.0'),
            state=Proforma.STATES.ISSUED,
            customer=customer
        )

        paired_proforma = ProformaFactory.create(
            transaction_currency='USD',
            transaction_xe_rate=Decimal('1.0'),
            state=Proforma.STATES.ISSUED,
            issue_date=timezone.now().date(),
            customer=customer
        )
        paired_invoice = paired_proforma.create_invoice()

        self.assertEqual(payment_method.transactions.count(), 0)

        payment_method.verified = True
        payment_method.save()

        self.assertEqual(lone_invoice.transactions.count(), 1)

        self.assertEqual(lone_proforma.transactions.count(), 1)

        self.assertEqual(list(paired_invoice.transactions),
                         list(paired_proforma.transactions))

        self.assertEqual(paired_invoice.transactions.count(), 1)
Esempio n. 20
0
    def test_add_transaction_with_amount_different_from_document(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        proforma = ProformaFactory.create(customer=customer,
                                          state=Proforma.STATES.ISSUED,
                                          issue_date=timezone.now().date())
        proforma.create_invoice()
        invoice = proforma.invoice

        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'valid_until':
            valid_until,
            'amount':
            invoice.total_in_transaction_currency + 1,
            'invoice':
            invoice_url,
            'proforma':
            proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [
                u"Transaction amount is different from it's "
                u"document's total_in_transaction_currency."
            ]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Esempio n. 21
0
    def test_not_allowed_methods(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        transaction_1 = TransactionFactory.create(payment_method=payment_method)
        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('transaction-detail',
                      kwargs={'customer_pk': customer.id,
                              'transaction_uuid': transaction_1.uuid})
        data = {
            'valid_until': valid_until
        }

        response = self.client.put(url, format='json', data=data)
        self.assertEqual(response.data['detail'], 'Method "PUT" not allowed.')

        response = self.client.post(url, format='json', data=data)
        self.assertEqual(response.data['detail'], 'Method "POST" not allowed.')
Esempio n. 22
0
    def test_not_allowed_methods(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        transaction_1 = TransactionFactory.create(payment_method=payment_method)
        valid_until = datetime.now()
        url = reverse('transaction-detail',
                      kwargs={'customer_pk': customer.id,
                              'transaction_uuid': transaction_1.uuid})
        data = {
            'valid_until': valid_until
        }

        response = self.client.put(url, format='json', data=data)
        self.assertEqual(response.data['detail'], 'Method "PUT" not allowed.')

        response = self.client.post(url, format='json', data=data)
        self.assertEqual(response.data['detail'], 'Method "POST" not allowed.')
Esempio n. 23
0
    def test_get_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        transaction = TransactionFactory.create(payment_method=payment_method)
        invoice = transaction.invoice
        proforma = transaction.proforma
        provider = invoice.provider

        expected = OrderedDict([
            ('id', unicode(transaction.uuid)),
            ('url',
             reverse('transaction-detail',
                     kwargs={
                         'customer_pk': customer.id,
                         'transaction_uuid': transaction.uuid
                     })),
            ('customer', reverse('customer-detail', args=[customer.pk])),
            ('provider', reverse('provider-detail', args=[provider.pk])),
            ('amount', unicode(Decimal('0.00') + transaction.amount)),
            ('currency', unicode(transaction.currency)),
            ('currency_rate_date', None),
            ('state', unicode(transaction.state)),
            ('proforma', reverse('proforma-detail', args=[proforma.pk])),
            ('invoice', reverse('invoice-detail', args=[invoice.pk])),
            ('can_be_consumed', transaction.can_be_consumed),
            ('payment_method',
             reverse('payment-method-detail',
                     kwargs={
                         'customer_pk': customer.id,
                         'payment_method_id': payment_method.id
                     })),
            ('pay_url',
             reverse('pay-transaction',
                     kwargs={'transaction_uuid': transaction.uuid})),
            ('valid_until', None)
        ])

        url = reverse('transaction-detail',
                      kwargs={
                          'customer_pk': customer.pk,
                          'transaction_uuid': transaction.uuid
                      })
        response = self.client.get(url, format='json')

        self.assertEqual(response.data, dict(expected))
    def test_fetch_transaction_status_call(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method, state=Transaction.States.Pending)

        mock_fetch_status = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            call_command('fetch_transactions_status')

            for transaction in transactions:
                self.assertIn(call(transaction),
                              mock_fetch_status.call_args_list)

            self.assertEqual(mock_fetch_status.call_count, len(transactions))
Esempio n. 25
0
    def test_filter_processor(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        # mysql does not store fractional time units but the object
        # created will have them so we can't use it directly
        #  to check the output
        payment_method.refresh_from_db()

        url = reverse('payment-method-list',
                      kwargs={'customer_pk': customer.pk})

        url_manual_processor = url + '?processor=manual'
        url_no_output = url + '?processor=random'

        self.assert_get_data(url_manual_processor, [payment_method])
        self.assert_get_data(url_no_output, [])
Esempio n. 26
0
    def test_add_transaction_with_unrelated_documents(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        invoice = InvoiceFactory.create(customer=customer)
        invoice.issue()
        invoice.save()

        proforma = ProformaFactory.create(customer=customer)
        proforma.issue()
        proforma.save()

        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'valid_until':
            valid_until,
            'amount':
            200.0,
            'invoice':
            invoice_url,
            'proforma':
            proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [u'Invoice and proforma are not related.']
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Esempio n. 27
0
    def test_no_transaction_creation_for_issued_documents_case3(self):
        """
            There are 1 pending and 1 settled transactions that together cover the document amount.
        """
        entry = DocumentEntryFactory(quantity=1, unit_price=100)
        invoice = InvoiceFactory.create(invoice_entries=[entry])
        invoice.issue()

        customer = invoice.customer
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=False,
        )

        TransactionFactory.create(invoice=invoice,
                                  payment_method=payment_method,
                                  amount=invoice.total_in_transaction_currency / 2,
                                  state=Transaction.States.Settled)

        TransactionFactory.create(invoice=invoice,
                                  payment_method=payment_method,
                                  amount=invoice.total_in_transaction_currency / 2,
                                  state=Transaction.States.Pending)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor, execute_transaction=mock_execute):
            expected_exception = ValidationError
            expected_message = "{'__all__': [u'Amount is greater than the amount that should be " \
                               "charged in order to pay the billing document.']}"
            try:
                TransactionFactory.create(invoice=invoice,
                                          payment_method=payment_method,
                                          amount=1)

                self.fail('{} not raised.'.format(str(expected_exception)))
            except expected_exception as e:
                self.assertEqual(str(e), expected_message)

            transactions = Transaction.objects.filter(
                payment_method=payment_method, invoice=invoice,
            )
            self.assertEqual(len(transactions), 2)

            self.assertEqual(mock_execute.call_count, 0)
    def test_no_transaction_creation_for_issued_documents_case3(self):
        """
            There are 1 pending and 1 settled transactions that together cover the document amount.
        """
        entry = DocumentEntryFactory(quantity=1, unit_price=100)
        invoice = InvoiceFactory.create(invoice_entries=[entry])
        invoice.issue()

        customer = invoice.customer
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, customer=customer,
            canceled=False,
            verified=False,
        )

        TransactionFactory.create(invoice=invoice,
                                  payment_method=payment_method,
                                  amount=invoice.total_in_transaction_currency / 2,
                                  state=Transaction.States.Settled)

        TransactionFactory.create(invoice=invoice,
                                  payment_method=payment_method,
                                  amount=invoice.total_in_transaction_currency / 2,
                                  state=Transaction.States.Pending)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor, execute_transaction=mock_execute):
            expected_exception = ValidationError
            expected_message = "Amount is greater than the amount that should be " \
                               "charged in order to pay the billing document."
            try:
                TransactionFactory.create(invoice=invoice,
                                          payment_method=payment_method,
                                          amount=1)

                self.fail('{} not raised.'.format(str(expected_exception)))
            except expected_exception as e:
                self.assertTrue(expected_message in str(e))

            transactions = Transaction.objects.filter(
                payment_method=payment_method, invoice=invoice,
            )
            self.assertEqual(len(transactions), 2)

            self.assertEqual(mock_execute.call_count, 0)
Esempio n. 29
0
    def test_add_transaction_without_currency_and_amount(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        entries = DocumentEntryFactory.create_batch(2)
        proforma = ProformaFactory.create(customer=customer,
                                          state=Proforma.STATES.ISSUED,
                                          issue_date=timezone.now().date(),
                                          currency='USD', transaction_currency='RON',
                                          transaction_xe_rate=Decimal('0.25'),
                                          proforma_entries=entries)
        proforma.create_invoice()
        invoice = proforma.related_document

        valid_until = datetime.now().replace(microsecond=0) + timedelta(minutes=30)
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk,
                              'payment_method_id': payment_method.pk})

        payment_method_url = reverse('payment-method-detail',
                                     kwargs={'customer_pk': customer.pk,
                                             'payment_method_id': payment_method.id})
        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method': reverse('payment-method-detail',
                                      kwargs={'customer_pk': customer.pk,
                                              'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'invoice': invoice_url,
            'proforma': proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.assertEqual(response.data['payment_method'], payment_method_url)
        self.assertEqual(response.data['valid_until'][:-1], valid_until.isoformat())
        self.assertEqual(response.data['can_be_consumed'], True)
        self.assertEqual(response.data['amount'],
                         force_text(invoice.total_in_transaction_currency))
        self.assertEqual(response.data['invoice'], invoice_url)
        self.assertEqual(response.data['proforma'], proforma_url)
        self.assertEqual(response.data['currency'], invoice.transaction_currency)
Esempio n. 30
0
    def test_exception_logging(self, mock_logger):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor, verified=True)

        TransactionFactory.create(payment_method=payment_method)

        mock_execute = MagicMock()
        mock_execute.side_effect = Exception('This happened.')

        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')
            expected_call = call(
                'Encountered exception while executing transaction with id=%s.',
                1,
                exc_info=True)

            self.assertEqual(expected_call, mock_logger.call_args)
Esempio n. 31
0
    def test_get_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        transaction = TransactionFactory.create(payment_method=payment_method)
        expected = self._transaction_data(transaction)

        with patch('silver.utils.payments._get_jwt_token') as mocked_token:
            mocked_token.return_value = 'token'

            url = reverse('transaction-detail',
                          kwargs={
                              'customer_pk': customer.pk,
                              'transaction_uuid': transaction.uuid
                          })
            response = self.client.get(url, format='json')

            self.assertEqual(response.data, dict(expected))
Esempio n. 32
0
    def test_create_one_without_required_fields(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        transaction = TransactionFactory.create(payment_method=payment_method)
        valid_until = datetime.now()

        data = {
            'valid_until': valid_until
        }

        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.id,
                              'payment_method_id': payment_method.id})

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.data['payment_method'],
                         ['This field is required.'])
Esempio n. 33
0
    def test_transaction_executing(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor
        )

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method
        )

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')

            for transaction in transactions:
                self.assertIn(call(transaction), mock_execute.call_args_list)

            self.assertEqual(mock_execute.call_count, len(transactions))
Esempio n. 34
0
    def test_add_transaction_with_documents_for_a_different_customer(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        proforma = ProformaFactory.create()
        proforma.state = proforma.STATES.ISSUED
        proforma.create_invoice()
        proforma.refresh_from_db()
        invoice = proforma.invoice

        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'valid_until':
            valid_until,
            'amount':
            200.0,
            'invoice':
            invoice_url,
            'proforma':
            proforma_url
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors':
            [u"Customer doesn't match with the one in documents."]
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    def test_transaction_executing(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            verified=True
        )

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method
        )

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')

            for transaction in transactions:
                self.assertIn(call(transaction), mock_execute.call_args_list)

            self.assertEqual(mock_execute.call_count, len(transactions))
Esempio n. 36
0
    def test_filter_min_max_amount(self):
        customer = CustomerFactory.create()
        payment = PaymentFactory.create(customer=customer, amount=100)
        payment_method_ok = PaymentMethodFactory.create(
            payment_processor='someprocessor', customer=customer)

        transaction = TransactionFactory.create(
            payment_method=payment_method_ok, payment=payment)
        transaction_data = self._transaction_data(customer, payment,
                                                  payment_method_ok,
                                                  transaction)

        urls = [
            reverse('payment-method-transaction-list',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method_ok.pk
                    }),
            reverse('transaction-list', kwargs={'customer_pk': customer.pk})
        ]

        for url in urls:
            url_with_filterable_data = url + '?min_amount=10'
            url_no_output = url + '?min_amount=150'

            response = self.client.get(url_with_filterable_data, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data[0], transaction_data)

            response = self.client.get(url_no_output, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, [])

            url_with_filterable_data = url + '?max_amount=1050'
            url_no_output = url + '?max_amount=10'

            response = self.client.get(url_with_filterable_data, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data[0], transaction_data)

            response = self.client.get(url_no_output, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, [])
Esempio n. 37
0
    def test_add_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        payment = PaymentFactory.create(customer=customer)
        valid_until = datetime.now()
        payment_method_url = reverse('payment-method-detail',
                                     kwargs={
                                         'customer_pk': customer.pk,
                                         'payment_method_id': payment_method.id
                                     })
        payment_url = reverse('payment-detail',
                              kwargs={
                                  'customer_pk': customer.pk,
                                  'payment_pk': payment.pk
                              })
        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })
        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'payment':
            reverse('payment-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_pk': payment.pk
                    }),
            'valid_until':
            valid_until
        }

        response = self.client.post(url, format='json', data=data).data

        self.assertEqual(response['payment_method'], payment_method_url)
        self.assertEqual(response['payment'], payment_url)
        self.assertEqual(response['valid_until'][:-1], valid_until.isoformat())
        self.assertEqual(response['is_usable'], False)
    def test_transaction_update_status_exception_logging(self, mock_logger):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)

        TransactionFactory.create(payment_method=payment_method,
                                  state=Transaction.States.Pending)

        mock_fetch_status = MagicMock()
        mock_fetch_status.side_effect = Exception('This happened.')

        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            call_command('fetch_transactions_status')
            expected_call = call(
                'Encountered exception while updating transaction with id=%s.',
                1,
                exc_info=True)

            self.assertEqual(expected_call, mock_logger.call_args)
    def test_encoding(self):
        now = timezone.now().replace(microsecond=0)
        payment_method = PaymentMethodFactory.create(added_at=now)

        factory = APIRequestFactory()
        url = reverse('payment-method-detail',
                      kwargs={
                          'payment_method_id': payment_method.pk,
                          'customer_pk': payment_method.customer.pk
                      })
        request = factory.get(url, format='json')

        serializer = PaymentMethodSerializer(payment_method,
                                             context={'request': request})

        self_url_skelet = 'http://testserver/customers/{}/payment_methods/{}/'
        transactions_url_skelet = "http://testserver/customers/{}/payment_methods/{}/transactions/"
        customer_url_skelet = 'http://testserver/customers/{}/'
        expected_data = OrderedDict([
            ('url',
             self_url_skelet.format(payment_method.customer.pk,
                                    payment_method.pk)),
            ('transactions',
             transactions_url_skelet.format(payment_method.customer.pk,
                                            payment_method.pk)),
            ('customer',
             customer_url_skelet.format(payment_method.customer.pk)),
            ('payment_processor_name', manual_processor),
            ('payment_processor',
             OrderedDict([
                 ("type", ManualProcessor.type), ("name", manual_processor),
                 ("allowed_currencies", []),
                 ("url", "http://testserver/payment_processors/manual/")
             ])),
            ('added_at', payment_method.added_at),
            ('verified', False),
            ('canceled', False),
            ('valid_until', None),
            ('display_info', None),
        ])

        json = JSONRenderer().render(serializer.data)
        self.assertEqual(json, JSONRenderer().render(expected_data))
Esempio n. 40
0
    def test_list_transactions(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        transaction_1 = TransactionFactory.create(payment_method=payment_method)
        expected_t1 = self._transaction_data(transaction_1)
        transaction_2 = TransactionFactory.create(payment_method=payment_method)
        expected_t2 = self._transaction_data(transaction_2)

        with patch('silver.utils.payments._get_jwt_token') as mocked_token:
            mocked_token.return_value = 'token'

            url = reverse('transaction-list',
                          kwargs={'customer_pk': customer.pk})

            response = self.client.get(url, format='json')

            self.assertEqual(response.data[1], expected_t1)
            self.assertEqual(response.data[0], expected_t2)
Esempio n. 41
0
    def test_filter_min_max_amount(self):
        customer = CustomerFactory.create()
        payment_method_ok = PaymentMethodFactory.create(
            payment_processor='someprocessor',
            customer=customer)

        transaction = TransactionFactory.create(
            payment_method=payment_method_ok,
            amount=100
        )
        transaction_data = self._transaction_data(transaction)

        urls = [
            reverse(
                'payment-method-transaction-list', kwargs={
                    'customer_pk': customer.pk,
                    'payment_method_id': payment_method_ok.pk}),
            reverse(
                'transaction-list', kwargs={'customer_pk': customer.pk})]

        for url in urls:
            url_with_filterable_data = url + '?min_amount=10'
            url_no_output = url + '?min_amount=150'

            response = self.client.get(url_with_filterable_data, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data[0], transaction_data)

            response = self.client.get(url_no_output, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, [])

            url_with_filterable_data = url + '?max_amount=1050'
            url_no_output = url + '?max_amount=10'

            response = self.client.get(url_with_filterable_data, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data[0], transaction_data)

            response = self.client.get(url_no_output, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, [])
    def test_encoding(self):
        now = timezone.now().replace(microsecond=0)
        payment_method = PaymentMethodFactory.create(added_at=now)

        factory = APIRequestFactory()
        url = reverse('payment-method-detail',
                      kwargs={'payment_method_id': payment_method.pk,
                              'customer_pk': payment_method.customer.pk})
        request = factory.get(url, format='json')

        serializer = PaymentMethodSerializer(payment_method, context={
            'request': request
        })

        self_url = build_absolute_test_url(url)
        transactions_url = build_absolute_test_url(
            reverse('payment-method-transaction-list',
                    [payment_method.pk, payment_method.customer.pk])
        )
        customer_url = build_absolute_test_url(
            reverse('customer-detail', [payment_method.customer.pk])
        )
        expected_data = OrderedDict([
            ('url', self_url),
            ('transactions', transactions_url),
            ('customer', customer_url),
            ('payment_processor_name', manual_processor),
            ('payment_processor', OrderedDict([
                ("type", ManualProcessor.type),
                ("name", manual_processor),
                ("allowed_currencies", []),
                ("url", build_absolute_test_url(reverse('payment-processor-detail', ['manual'])))
            ])),
            ('added_at', payment_method.added_at),
            ('verified', False),
            ('canceled', False),
            ('valid_until', None),
            ('display_info', None),
        ])

        json = JSONRenderer().render(serializer.data)
        self.assertEqual(json, JSONRenderer().render(expected_data))
    def test_fetch_transaction_status_call(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor
        )

        transactions = TransactionFactory.create_batch(
            5, payment_method=payment_method, state=Transaction.States.Pending
        )

        mock_fetch_status = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            call_command('fetch_transactions_status')

            for transaction in transactions:
                self.assertIn(call(transaction),
                              mock_fetch_status.call_args_list)

            self.assertEqual(mock_fetch_status.call_count,
                             len(transactions))
    def test_transaction_update_status_exception_logging(self, mock_logger):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor
        )

        TransactionFactory.create(payment_method=payment_method,
                                  state=Transaction.States.Pending)

        mock_fetch_status = MagicMock()
        mock_fetch_status.side_effect = Exception('This happened.')

        with patch.multiple(TriggeredProcessor,
                            fetch_transaction_status=mock_fetch_status):
            call_command('fetch_transactions_status')
            expected_call = call(
                'Encountered exception while updating transaction with id=%s.',
                1, exc_info=True
            )

            self.assertEqual(expected_call, mock_logger.call_args)
Esempio n. 45
0
    def test_transaction_list(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        payment = PaymentFactory.create(customer=customer)

        transaction_1 = TransactionFactory.create(
            payment_method=payment_method, payment=payment)
        expected_t1 = self._transaction_data(customer, payment, payment_method,
                                             transaction_1)

        transaction_2 = TransactionFactory.create(
            payment_method=payment_method, payment=payment)
        expected_t2 = self._transaction_data(customer, payment, payment_method,
                                             transaction_2)

        url = reverse('transaction-list', kwargs={'customer_pk': customer.pk})

        response = self.client.get(url, format='json')
        self.assertEqual(response.data[0], expected_t1)
        self.assertEqual(response.data[1], expected_t2)
    def test_exception_logging(self, mock_logger):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            verified=True
        )

        TransactionFactory.create(payment_method=payment_method)

        mock_execute = MagicMock()
        mock_execute.side_effect = Exception('This happened.')

        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            call_command('execute_transactions')
            expected_call = call(
                'Encountered exception while executing transaction with id=%s.',
                1, exc_info=True
            )

            self.assertEqual(expected_call, mock_logger.call_args)
Esempio n. 47
0
    def test_add_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        proforma = ProformaFactory.create(customer=customer)
        proforma.state = proforma.STATES.ISSUED
        proforma.create_invoice()
        proforma.refresh_from_db()
        invoice = proforma.invoice

        payment_method_url = reverse('payment-method-detail', kwargs={'customer_pk': customer.pk,
                                                                      'payment_method_id': payment_method.id})
        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])

        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk, 'payment_method_id': payment_method.pk})
        valid_until = datetime.now() + timedelta(minutes=30)
        currency = 'USD'
        data = {
            'payment_method': reverse('payment-method-detail', kwargs={'customer_pk': customer.pk,
                                                                       'payment_method_id': payment_method.id}),
            'amount': '200.0',
            'invoice': invoice_url,
            'proforma': proforma_url,
            'valid_until': valid_until,
            'currency': currency,
        }

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.assertEqual(response.data['payment_method'], payment_method_url)
        self.assertEqual(response.data['valid_until'][:-1], valid_until.isoformat())
        self.assertEqual(response.data['can_be_consumed'], True)
        self.assertEqual(response.data['amount'], '200.00')
        self.assertEqual(response.data['invoice'], invoice_url)
        self.assertEqual(response.data['proforma'], proforma_url)
        self.assertEqual(response.data['currency'], currency)

        self.assertTrue(Transaction.objects.filter(uuid=response.data['id']))
    def test_create_transaction_with_not_allowed_currency(self):
        invoice = InvoiceFactory.create(transaction_currency='EUR',
                                        transaction_xe_rate=Decimal('1.0'),
                                        state=Invoice.STATES.ISSUED)
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=invoice.customer,
            canceled=False,
            verified=False)

        expected_exception = ValidationError
        expected_message = '{\'__all__\': ["Currency EUR is not allowed by ' \
                           'the payment method. Allowed currencies are ' \
                           '[\'RON\', \'USD\']."]}'

        try:
            TransactionFactory.create(payment_method=payment_method,
                                      invoice=invoice)
            self.fail('{} not raised.'.format(str(expected_exception)))
        except expected_exception as e:
            self.assertEqual(expected_message, str(e))
    def test_create_transaction_with_not_allowed_currency(self):
        invoice = InvoiceFactory.create(transaction_currency='EUR',
                                        transaction_xe_rate=Decimal('1.0'),
                                        state=Invoice.STATES.ISSUED)
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=invoice.customer,
            canceled=False,
            verified=False
        )

        expected_exception = ValidationError
        expected_message = 'Currency EUR is not allowed by ' \
                           'the payment method. Allowed currencies are ' \
                           '[\'RON\', \'USD\'].'
        try:
            TransactionFactory.create(payment_method=payment_method,
                                      invoice=invoice)
            self.fail('{} not raised.'.format(str(expected_exception)))
        except expected_exception as e:
            self.assertTrue(expected_message in str(e))
Esempio n. 50
0
    def test_add_transaction_without_documents(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        valid_until = datetime.now()
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk, 'payment_method_id': payment_method.pk})
        data = {
            'payment_method': reverse('payment-method-detail', kwargs={'customer_pk': customer.pk,
                                                                       'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'amount': 200.0,
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [u'The transaction must have at '
                                 u'least one document (invoice or proforma).']
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Esempio n. 51
0
    def test_get_transaction_details(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        payment = PaymentFactory.create(customer=customer)
        transaction_1 = TransactionFactory.create(
            payment_method=payment_method, payment=payment)
        expected_t1 = OrderedDict([
            ('url',
             reverse('transaction-detail',
                     kwargs={
                         'customer_pk': customer.pk,
                         'transaction_uuid': transaction_1.uuid
                     })),
            ('payment_method',
             reverse('payment-method-detail',
                     kwargs={
                         'customer_pk': customer.pk,
                         'payment_method_id': payment_method.id
                     })),
            ('payment',
             reverse('payment-detail',
                     kwargs={
                         'customer_pk': customer.pk,
                         'payment_pk': transaction_1.payment.pk
                     })),
            ('is_usable', True),
            ('pay_url',
             reverse('pay-transaction',
                     kwargs={'transaction_uuid': transaction_1.uuid})),
            ('valid_until', None),
        ])

        url = reverse('transaction-detail',
                      kwargs={
                          'customer_pk': customer.pk,
                          'transaction_uuid': transaction_1.uuid
                      })
        response = self.client.get(url, format='json')
        self.assertEqual(response.data, dict(expected_t1))
Esempio n. 52
0
    def test_filter_payment_method(self):
        customer = CustomerFactory.create()
        payment = PaymentFactory.create(customer=customer)
        payment_method = PaymentMethodFactory.create(
            payment_processor='someprocessor', customer=customer)

        transaction1 = TransactionFactory.create(payment_method=payment_method,
                                                 payment=payment)
        transaction_data_1 = self._transaction_data(customer, payment,
                                                    payment_method,
                                                    transaction1)

        transaction2 = TransactionFactory.create(payment_method=payment_method,
                                                 payment=payment)
        transaction_data_2 = self._transaction_data(customer, payment,
                                                    payment_method,
                                                    transaction2)

        urls = [
            reverse('payment-method-transaction-list',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.pk
                    }),
            reverse('transaction-list', kwargs={'customer_pk': customer.pk})
        ]

        for url in urls:
            url_method_someprocessor = url + '?payment_method=someprocessor'
            url_no_output = url + '?payment_method=Random'

            response = self.client.get(url_method_someprocessor, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data[0], transaction_data_1)
            self.assertEqual(response.data[1], transaction_data_2)

            response = self.client.get(url_no_output, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, [])
Esempio n. 53
0
    def test_no_transaction_creation_for_issued_documents_case3(self):
        """
            There already is an active (initial/pending) transaction for the
            document.
        """
        invoice = InvoiceFactory.create()
        invoice.issue()
        customer = invoice.customer
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=customer,
            canceled=False,
            verified=True,
        )

        transaction = TransactionFactory.create(invoice=invoice,
                                                payment_method=payment_method)

        mock_execute = MagicMock()
        with patch.multiple(TriggeredProcessor,
                            execute_transaction=mock_execute):
            expected_exception = ValidationError
            expected_message = "{'__all__': [u'There already are active " \
                               "transactions for the same billing documents.']}"
            try:
                TransactionFactory.create(invoice=invoice,
                                          payment_method=payment_method)
                self.fail('{} not raised.'.format(str(expected_exception)))
            except expected_exception as e:
                self.assertEqual(str(e), expected_message)

            transactions = Transaction.objects.filter(
                payment_method=payment_method,
                invoice=invoice,
            )
            self.assertEqual(len(transactions), 1)
            self.assertEqual(transactions[0], transaction)

            self.assertEqual(mock_execute.call_count, 0)
    def customer(self):
        c = CustomerFactory.create(consolidated_billing=False,
                                   sales_tax_percent=Decimal('0.00'))

        c.meta = {
            "cardNumber": "4111111111111111",
            "expirationDate": "2020-12",
            "cardCode": "123",
        }

        c.save()

        auth = 'AuthorizeNetTriggered'
        null = 'manual'
        pm = PaymentMethodFactory.create(customer=c,
                                         verified=True,
                                         canceled=False,
                                         display_info="pytest",
                                         payment_processor=auth)
        pm.save()

        return c
    def _create_default_payment_method(self):
        # 0 for easy asserting.
        customer = CustomerFactory(sales_tax_percent=0,
                                   currency='USD',
                                   first_name="Captain",
                                   last_name="Hook")

        # Create customer payment method
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor,
            customer=customer,
            canceled=False,
            verified=True,
            data={
                # Wait until payment day X to begin retry attempts
                'attempt_retries_after': 2,

                # Stop attempts on day X
                'stop_retry_attempts': 5,
            })

        return customer, payment_method
Esempio n. 56
0
    def test_patch_transaction_with_initial_status(self):
        payment_method = PaymentMethodFactory.create(
            payment_processor=triggered_processor)

        transaction = TransactionFactory.create(payment_method=payment_method)

        url = reverse('transaction-detail',
                      args=[transaction.customer.pk, transaction.uuid])

        valid_until = timezone.now().replace(microsecond=0)

        data = {
            'valid_until': valid_until,
        }

        response = self.client.patch(url, format='json', data=data)

        self.assertEqual(
            response.status_code, status.HTTP_200_OK,
            "status %s, data %s" % (response.status_code, response.data))

        transaction.refresh_from_db()
        self.assertEqual(transaction.valid_until, valid_until)
Esempio n. 57
0
    def test_add_transaction_without_documents(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)
        valid_until = datetime.now().replace(microsecond=0)
        url = reverse('payment-method-transaction-list',
                      kwargs={'customer_pk': customer.pk,
                              'payment_method_id': payment_method.pk})
        data = {
            'payment_method': reverse('payment-method-detail',
                                      kwargs={'customer_pk': customer.pk,
                                              'payment_method_id': payment_method.id}),
            'valid_until': valid_until,
            'amount': 200.0,
        }

        response = self.client.post(url, format='json', data=data)

        expected_data = {
            'non_field_errors': [u'The transaction must have at least one billing document '
                                 u'(invoice or proforma).']
        }
        self.assertEqual(response.data, expected_data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Esempio n. 58
0
    def test_filter_payment_method(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(
            payment_processor='someprocessor',
            customer=customer)

        transaction1 = TransactionFactory.create(
            payment_method=payment_method
        )
        transaction_data_1 = self._transaction_data(transaction1)

        transaction2 = TransactionFactory.create(
            payment_method=payment_method
        )
        transaction_data_2 = self._transaction_data(transaction2)

        urls = [
            reverse(
                'payment-method-transaction-list', kwargs={
                    'customer_pk': customer.pk,
                    'payment_method_id': payment_method.pk}),
            reverse(
                'transaction-list', kwargs={'customer_pk': customer.pk})]

        for url in urls:
            url_method_someprocessor = url + '?payment_method=someprocessor'
            url_no_output = url + '?payment_method=Random'

            response = self.client.get(url_method_someprocessor, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data[0], transaction_data_1)
            self.assertEqual(response.data[1], transaction_data_2)

            response = self.client.get(url_no_output, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
            self.assertEqual(response.data, [])
Esempio n. 59
0
    def test_add_transaction(self):
        customer = CustomerFactory.create()
        payment_method = PaymentMethodFactory.create(customer=customer)

        entry = DocumentEntryFactory(quantity=1, unit_price=200)
        proforma = ProformaFactory.create(customer=customer,
                                          proforma_entries=[entry])
        proforma.state = proforma.STATES.ISSUED
        proforma.create_invoice()
        proforma.refresh_from_db()
        invoice = proforma.invoice

        payment_method_url = reverse('payment-method-detail',
                                     kwargs={
                                         'customer_pk': customer.pk,
                                         'payment_method_id': payment_method.id
                                     })

        invoice_url = reverse('invoice-detail', args=[invoice.pk])
        proforma_url = reverse('proforma-detail', args=[proforma.pk])

        url = reverse('payment-method-transaction-list',
                      kwargs={
                          'customer_pk': customer.pk,
                          'payment_method_id': payment_method.pk
                      })

        valid_until = datetime.now().replace(microsecond=0) + timedelta(
            minutes=30)

        currency = invoice.transaction_currency

        data = {
            'payment_method':
            reverse('payment-method-detail',
                    kwargs={
                        'customer_pk': customer.pk,
                        'payment_method_id': payment_method.id
                    }),
            'amount':
            invoice.transaction_total,
            'invoice':
            invoice_url,
            'proforma':
            proforma_url,
            'valid_until':
            valid_until,
            'currency':
            currency,
        }

        response = self.client.post(url, format='json', data=data)

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        self.assertEqual(response.data['payment_method'], payment_method_url)
        self.assertEqual(response.data['valid_until'][:-1],
                         valid_until.isoformat())
        self.assertEqual(response.data['can_be_consumed'], True)
        self.assertEqual(response.data['amount'],
                         unicode(Decimal('0.00') + invoice.transaction_total))
        self.assertEqual(response.data['invoice'], invoice_url)
        self.assertEqual(response.data['proforma'], proforma_url)
        self.assertEqual(response.data['currency'], currency)

        self.assertTrue(Transaction.objects.filter(uuid=response.data['id']))
Esempio n. 60
0
    def create_payment_method(self, *args, **kwargs):
        payment_method = PaymentMethodFactory.create(*args, **kwargs)
        payment_method.added_at.replace(microsecond=0)

        return payment_method