def test_payment_get(self): empty_response = self.client.get('/api/payments/') self.assertEqual(empty_response.status_code, 200) self.assertEqual(empty_response.data, []) payment1 = Payment( sender=self.sender_user, receiver=self.receiver_user, amount=10 ) payment1.save() payment2 = Payment( sender=self.receiver_user, receiver=self.sender_user, amount=50 ) payment2.save() payment3 = Payment( sender=self.receiver_user, receiver=self.friend_of_receiver, amount=50, ) payment3.save() response = self.client.get('/api/payments/') self.assertEqual(len(response.data), 2) first_payment = response.data[0] self.assertEqual(first_payment['sender']['username'], 'admin') self.assertEqual(first_payment['receiver']['username'], 'oriol') self.assertEqual(first_payment['amount'], '10.00') second_payment = response.data[1] self.assertEqual(second_payment['sender']['username'], 'oriol') self.assertEqual(second_payment['receiver']['username'], 'admin') self.assertEqual(second_payment['amount'], '50.00')
def test_post(self): self._give_user_permissions() self.user2 = Member.objects.create( username="******", first_name="Test2", last_name="Example", email="*****@*****.**", ) Profile.objects.create(user=self.user2) self.user2 = PaymentUser.objects.get(pk=self.user2.pk) BankAccount.objects.create( last_used=timezone.now(), owner=self.user, iban="DE75512108001245126199", mandate_no="2", valid_from=timezone.now(), initials="T.E.S.T.", last_name="ersssss", ) BankAccount.objects.create( last_used=timezone.now(), owner=self.user2, iban="NL02ABNA0123456789", mandate_no="1", valid_from=timezone.now(), initials="T.E.S.T.", last_name="ersssss2", ) Payment.objects.bulk_create( [ Payment( amount=1, paid_by=self.user, type=Payment.TPAY, batch=self.batch ), Payment( amount=2, paid_by=self.user, type=Payment.TPAY, batch=self.batch ), Payment( amount=4, paid_by=self.user2, type=Payment.TPAY, batch=self.batch ), Payment( amount=2, paid_by=self.user2, type=Payment.TPAY, batch=self.batch ), ] ) response = self.client.post(f"/admin/payments/batch/{self.batch.id}/export/") self.assertEqual( response.content, b"Account holder,IBAN,Mandate Reference,Amount,Description,Mandate Date\r\n" b"T.E.S.T. ersssss,DE75512108001245126199,2,3.00,Thalia Pay payments for 2020-1,2020-01-01\r\n" b"T.E.S.T. ersssss2,NL02ABNA0123456789,1,6.00,Thalia Pay payments for 2020-1,2020-01-01\r\n", )
def test_two_seats_all_paid(self, appointment): ser = s.AppointmentSerializer() seat1 = Seat(appointment=appointment, birth_date=timezone.now()) seat1.save() payment1 = Payment(amount=200, seat=seat1, paid_at=timezone.now()) payment1.save() seat2 = Seat(appointment=appointment, birth_date=timezone.now()) seat2.save() payment2 = Payment(amount=200, seat=seat2, paid_at=timezone.now()) payment2.save() assert ser.get_all_seats_paid(appointment) is True
def test_seat_with_0_amount_paid(self, appointment): ser = s.AppointmentSerializer() seat = Seat(appointment=appointment, birth_date=timezone.now()) seat.save() payment = Payment(amount=0, seat=seat, paid_at=timezone.now()) payment.save() assert ser.get_all_seats_paid(appointment) is True
def test_buy_periodic_release_only_for_paid_orders(self, coverable, run_release): coverable.return_value = True self._create_order(pair_name='BTCEUR') pref = PaymentPreference( provider_system_id='wawytha', payment_method=PaymentMethod.objects.get( name__icontains='Safe Charge' ) ) pref.save() payment = Payment( order=self.order, currency=self.order.pair.quote, payment_preference=pref, amount_cash=self.order.amount_quote, is_success=True, is_redeemed=False ) payment.save() buy_order_release_reference_periodic.apply_async() run_release.assert_not_called() self.order.status = Order.PAID self.order.save() buy_order_release_reference_periodic.apply_async() run_release.assert_called_once()
def _two_checkout_payment(request): pst = request.POST order_id = pst.get('vendor_order_id') if not order_id: return try: order = Task.objects.all().filter(id=order_id) except (TypeError, ValueError): # order_id is not an integer return order = order and order[0] if order: vals = { 'sale_id': request.POST.get('sale_id'), 'customer_ip': request.POST.get('customer_ip'), 'amount': request.POST.get('invoice_usd_amount') } order.status = co.UNPROCESSED order.save() payment = Payment(powner=order.owner, ptask=order, values=json.dumps(vals), payment_status=co.IN_PROCESS, payment_type=co.TWOCHECKOUT) payment.save()
def test_create_payment(self): with self.subTest("Creates new payment with right payment type"): p = services.create_payment(MockPayable(self.member), self.member, Payment.CASH) self.assertEqual(p.amount, 5) self.assertEqual(p.topic, "mock topic") self.assertEqual(p.notes, "mock notes") self.assertEqual(p.paid_by, self.member) self.assertEqual(p.processed_by, self.member) self.assertEqual(p.type, Payment.CASH) with self.subTest("Updates payment if one already exists"): existing_payment = Payment(amount=2) p = services.create_payment( MockPayable(payer=self.member, payment=existing_payment), self.member, Payment.CASH, ) self.assertEqual(p, existing_payment) self.assertEqual(p.amount, 5) with self.subTest("Does not allow Thalia Pay when not enabled"): with self.assertRaises(PaymentError): services.create_payment(MockPayable(payer=self.member), self.member, Payment.TPAY) with self.subTest("Do not allow zero euro payments"): with self.assertRaises(PaymentError): services.create_payment( MockPayable(payer=self.member, amount=0), self.member, Payment.TPAY)
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'), )
def charge(self): cleaned_data = self.clean() cause = Cause.objects.get(pk=cleaned_data['cause_id']) amount = int(cleaned_data['amount'] * 100) if amount < self.resource.min_price: raise forms.ValidationError('You hacker!') stripe.api_key = settings.STRIPE_API_SECRET_KEY token = cleaned_data['stripeToken'] payment = Payment( user=self.user, resource=self.resource, amount=amount, cause=cause, token=token, ) try: stripe.Charge.create( amount=amount, currency='bgn', card=token, description=str(payment) ) except stripe.CardError as e: raise forms.ValidationError(e) payment.save()
def test_delete_payment(self): sender = User.objects.create_user(username=USER_TEST1['username'], email=USER_TEST1['email'], password=USER_TEST1['password']) recipient = User.objects.create_user(username=USER_TEST2['username'], email=USER_TEST2['email'], password=USER_TEST2['password']) TEST_PAYMENT_DATA = { 'amount': 25000, 'details': 'Payment Description', 'sender': sender, 'recipient': recipient } self.assertTrue(Payment.objects.count() == 0) payment = Payment(**TEST_PAYMENT_DATA) payment.save() self.assertTrue(Payment.objects.count() == 1) self.assertTrue( Payment.objects.filter(payment_uuid=payment.payment_uuid, is_validated=False).exists()) payment.delete() self.assertTrue(Payment.objects.count() == 0) self.assertFalse( Payment.objects.filter(payment_uuid=payment.payment_uuid, is_validated=False).exists())
def test_is_frozen_if_paid_internally(self): order = Order(**self.data) order.is_paid = True order.save() payment_method = PaymentMethod(name='Internal Test', is_internal=True) payment_method.save() pref = PaymentPreference(payment_method=payment_method, user=order.user, identifier='InternalTestIdentifier') pref.save() payment = Payment(payment_preference=pref, amount_cash=order.amount_cash, order=order, user=order.user, currency=order.currency) payment.save() order = Order.objects.last() # it's paid self.assertTrue(order.is_paid) # therefore it's frozen self.assertTrue(order.payment_status_frozen) # even though deadline is in the future self.assertTrue(order.payment_deadline >= timezone.now())
def test_send_qrcode(): code = "0123-123456-1111" licence_plate = "ABC123" location_name = "Test Location" full_name = "Gipsz Jakab" location = m.Location(name=location_name) appointment = m.Appointment( start=dt.datetime(2020, 4, 24, 9, 10), location=location, normalized_licence_plate=licence_plate ) payment = Payment( amount=24_980, payment_method_type=PaymentMethodType.ON_SITE, product_type=ProductType.NORMAL_EXAM, ) seat = m.Seat( full_name=full_name, birth_date=timezone.now(), email="*****@*****.**", appointment=appointment, qrcode=m.QRCode(code=code), payment=payment, ) email.send_qrcode(seat) assert len(mail.outbox) == 1 sent_mail = mail.outbox[0] assert full_name in sent_mail.body assert licence_plate in sent_mail.body assert location.name in sent_mail.body assert "Helyszínen" in sent_mail.body assert "Test Location" in sent_mail.body assert code in sent_mail.body assert "\nFizetendő összeg: 24980 Ft\n" in sent_mail.body assert "\nVizsgálat típusa: Normál vizsgálat\n" in sent_mail.body assert "A normál vizsgálatok eredményét 72 órán belül küldjük Önnek." in sent_mail.body
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()
def test_get_fee_amounts(self): event = Event.objects.get(pk=6) course = Course.objects.get(pk=1) holes = list(course.holes.all()) event_fees = list(EventFee.objects.filter(event=6).all()) registration = Registration(event=event, course=course, starting_hole=2, starting_order=0) player1 = Player(id=1, email="*****@*****.**") player2 = Player(id=2, email="*****@*****.**") user1 = User(id=1, email="*****@*****.**") slot1 = RegistrationSlot(event=event, registration=registration, hole=holes[0], player=player1, starting_order=0, slot=0, status="R") slot2 = RegistrationSlot(event=event, registration=registration, hole=holes[0], player=player2, starting_order=0, slot=1, status="R") payment = Payment(event=event, user=user1, payment_code="test", notification_type="C", confirmed=1) payment_details = [ RegistrationFee(id=1, event_fee=event_fees[0], registration_slot=slot1, payment=payment), RegistrationFee(id=2, event_fee=event_fees[1], registration_slot=slot1, payment=payment), RegistrationFee(id=3, event_fee=event_fees[3], registration_slot=slot1, payment=payment), RegistrationFee(id=4, event_fee=event_fees[0], registration_slot=slot2, payment=payment), RegistrationFee(id=5, event_fee=event_fees[2], registration_slot=slot2, payment=payment) ] required_fees = get_required_fees(event, payment_details) optional_fees = get_optional_fees(event, payment_details) self.assertEqual(Decimal(10), required_fees) self.assertEqual(Decimal(29), optional_fees)
def test_not_creates_for_from_account_and_incoming(self): payment = Payment( **self.payment_data, from_account=self.bob_account, direction=PaymentDirections.OUTGOING.name, ) self.assertRaises(ValidationError, Payment.full_clean, payment)
def test_not_creates_for_same_accounts(self): payment = Payment( **self.payment_data, to_account=self.alice_account, direction=PaymentDirections.OUTGOING.name, ) self.assertRaises(ValidationError, Payment.full_clean, payment)
def test_payment_delete_view(self): payment = Payment(amount=10) payment.save() url = reverse('payments-delete', args=[payment.id]) response = self.client.get(url) self.assertEqual(response.status_code, 302)
def save(self, *args, **kwargs): res = super(NewTaskForm, self).save(*args, **kwargs) # Add unpaid payment. payment = Payment(powner=self.request.user, ptask=self.instance, values='{}', payment_status=co.UNPAID) payment.save() return res
def test_payment_str(self): """ Test a payment string rep is maint request title """ rental = Rental(address='Test address') maint_request = MaintRequest(property_ref=rental, title='test request') payment = Payment(maint_request=maint_request, amount=10) self.assertTrue(str(payment), maint_request.title)
def test_not_creates_for_zero_amount(self): payment = Payment( account=self.alice_account, to_account=self.bob_account, direction=PaymentDirections.OUTGOING.name, amount=0, ) self.assertRaises(ValidationError, Payment.full_clean, payment)
def test_url_is_resolved(self): """ test url uses correct view """ rental = Rental(address='11 Test Street') maint_request = MaintRequest(property_ref=rental, title='test') payment = Payment(id=1, maint_request=maint_request, amount=50) url = reverse('checkout', args=[payment.id]) self.assertEqual(resolve(url).func, checkout)
def test_str_representation(self): obliged = Obliged(full_name='Example Name', email='*****@*****.**') payment = Payment(name='Example_Name', payment_code='100-200-300', description='This is a test', amount=20.33, obliged=obliged, date='2020-05-04') self.assertEqual(str(payment), payment.name)
def test_process_payment(self): self.e1.username = "******" self.e1.save() self.e2.username = "******" self.e2.save() # Check that the DoesNotExist is caught p = Payment(amount=10, type=Payment.CARD) services.process_payment(p) p0 = services._create_payment_for_entry(self.e0) self.e0.payment = p0 self.e0.save() p1 = services._create_payment_for_entry(self.e1) self.e1.payment = p1 self.e1.save() p2 = services._create_payment_for_entry(self.e2) self.e2.payment = p2 self.e2.save() p3 = services._create_payment_for_entry(self.e3) self.e3.payment = p3 self.e3.save() Entry.objects.filter( pk__in=[self.e1.pk, self.e2.pk, self.e3.pk]).update( status=Entry.STATUS_ACCEPTED) payments = Payment.objects.filter(pk__in=[p0.pk, p2.pk, p3.pk]) payments.update(type=Payment.CARD) for payment in Payment.objects.filter(pk__in=[p0.pk, p1.pk, p2.pk]): services.process_payment(payment) self.e0.refresh_from_db() self.e1.refresh_from_db() self.e2.refresh_from_db() self.assertEqual(self.e0.status, Entry.STATUS_REVIEW) self.assertEqual(self.e1.status, Entry.STATUS_ACCEPTED) self.assertEqual(self.e2.status, Entry.STATUS_COMPLETED) p0.type = Payment.CARD p0.save() self.e0.status = Entry.STATUS_ACCEPTED self.e0.save() services.process_payment(p0) self.assertEqual(self.e0.status, Entry.STATUS_ACCEPTED) p3.refresh_from_db() services.process_payment(p3) self.e3.refresh_from_db() self.assertEqual(self.e3.status, Entry.STATUS_COMPLETED) self.assertEqual(len(mail.outbox), 2)
def test_already_paid(self, messages_error): self.payable.payment = Payment(amount=8) response = self.client.post( reverse("payments:payment-process"), follow=False, data=self.test_body ) messages_error.assert_called_with(ANY, "This object has already been paid for.") self.assertEqual(302, response.status_code) self.assertEqual("/mock_next", response.url)
def make_a_booking(request, pk): route = TravelRoute.objects.get(pk=pk) user = CustomUser() if not request.user.is_authenticated: messages.info(request, "Please login to proceed with booking.") elif request.method == "POST": form = request.POST # get form values booking = Booking() # get route price route = TravelRoute.objects.get(pk=pk) price = route.price booking.route = route booking.bus_details = Bus.objects.get(pk=form["bus_id"]) booking.customer_details = CustomUser.objects.get(pk=form["user_id"]) booking.number_of_tickets = request.POST["number_of_tickets"] booking.date_of_booking = request.POST["date_of_booking"] booking.amount_paid = int(booking.number_of_tickets) * int(price) cl = MpesaClient() token = cl.access_token print(token) # Use a Safaricom phone number that you have access to, for you to be able to view the prompt. phone_number = request.POST["mobile_number"] print(phone_number) amount = booking.amount_paid account_reference = "Msafiri Ticket" transaction_desc = "Description" callback_url = request.build_absolute_uri( reverse("mpesa_stk_push_callback")) print(callback_url) response = cl.stk_push(phone_number, amount, account_reference, transaction_desc, callback_url) # stay on payment page then redirect if successful # return HttpResponse(response.text) # payment payment = Payment() payment.customer_details = booking.customer_details payment.amount_paid = booking.amount_paid payment.mode_of_payment = ModeOfPayment.objects.get(pk=1) payment.payment_for = booking booking.save() payment.save() messages.success(request, "Booking successful.") return redirect("bookings:booking_detail", booking.pk) bookings = Booking.objects.all() context = { "route": route, "bookings": bookings, } return render(request, "bookings/booking.html", context)
def test_not_creates_for_accounts_with_different_currencies(self): self.bob_account.currency = Currencies.USD self.bob_account.save() payment = Payment( **self.payment_data, to_account=self.bob_account, direction=PaymentDirections.OUTGOING.name, ) self.assertRaises(ValidationError, Payment.full_clean, payment)
def rsvp(request): response = {'errors': {}} form = WebRSVPForm(request.POST) if form.is_valid(): cd = form.cleaned_data for key, value in request.POST.items(): words = key.split('_') if words[0] == 'unnamed': guest = Guest.objects.get(pk=int(words[-1])) if words[1] == 'first': guest.first_name = value elif words[1] == 'last': guest.last_name = value guest.save() guest = Guest.objects.get(id=cd['guest_id']) payment = None if cd['attending'] and cd['nights_onsite'] > 0: # The guest(s) will be staying onsite, so we need payment amount = lodging_cost(cd['guests'], cd['nights_onsite']) try: stripe_kwargs = { 'amount': int(amount * 100), # Convert dollars to cents 'currency': 'usd', 'source': cd['stripe_token'], 'description': "Lodging for Tony & Haya's Wedding"} if guest.email: stripe_kwargs['receipt_email'] = guest.email charge = stripe.Charge.create(**stripe_kwargs) payment = Payment( amount=amount, payer=Payer.objects.get_or_create(guest=guest)[0], category=PaymentCategory.objects.get(name='Lodging'), stripe_id=charge.id) payment.save() except stripe.error.CardError as card_error: # There was an error processing the credit card card_error = str(card_error) if 'Request req' in card_error: card_error = card_error.split(':', 1)[1].strip() response['errors']['rsvp_cc'] = [card_error] if not response['errors']: rsvp = form.save() if payment: rsvp.payment = payment rsvp.save() else: # The form is invalid response['errors'] = form.errors return JsonResponse(response)
def test_get_attribute(self, mock_super): field = PaymentTypeField(choices=Payment.PAYMENT_TYPE) obj = Payment() obj.payment = False self.assertEqual(field.get_attribute(obj), PaymentTypeField.NO_PAYMENT) obj.payment = True field.get_attribute(obj) mock_super.assert_called()
def test_is_created(self): payment = Payment( **self.payment_data, to_account=self.bob_account, direction=PaymentDirections.OUTGOING.name, ) payment.full_clean() payment.save() payments = Payment.objects.filter(account=self.alice_account.id) self.assertEqual(len(payments.all()), 1)
def test_get(self): self._give_user_permissions() Payment.objects.bulk_create( [ Payment( amount=1, type=Payment.TPAY, created_at=timezone.datetime(2020, 1, 31, tzinfo=timezone.utc), ), Payment( amount=2, type=Payment.TPAY, created_at=timezone.datetime(2020, 2, 1, tzinfo=timezone.utc), ), Payment( amount=3, type=Payment.TPAY, created_at=timezone.datetime(2020, 2, 10, tzinfo=timezone.utc), batch=self.batch, ), Payment( amount=4, type=Payment.TPAY, created_at=timezone.datetime(2020, 2, 28, tzinfo=timezone.utc), ), Payment( amount=5, type=Payment.TPAY, created_at=timezone.datetime(2020, 2, 29, tzinfo=timezone.utc), ), Payment( amount=6, type=Payment.TPAY, created_at=timezone.datetime(2020, 3, 1, tzinfo=timezone.utc), ), Payment( amount=7, type=Payment.WIRE, created_at=timezone.datetime(2020, 1, 1, tzinfo=timezone.utc), ), ] ) self.client.get("/admin/payments/batch/new_filled/") b = Batch.objects.exclude(id=self.batch.id).first() self.assertEqual(Payment.objects.get(amount=1).batch.id, b.id) self.assertEqual(Payment.objects.get(amount=2).batch.id, b.id) self.assertEqual(Payment.objects.get(amount=3).batch.id, self.batch.id) self.assertEqual(Payment.objects.get(amount=4).batch.id, b.id) self.assertEqual(Payment.objects.get(amount=5).batch.id, b.id) self.assertEqual(Payment.objects.get(amount=6).batch.id, b.id) self.assertIsNone(Payment.objects.get(amount=7).batch)