Exemplo n.º 1
0
def save_payments_list_view(a_request, username):
	
	if a_request.method != 'POST':
		return HttpResponseNotFound('<h1>No Page Here</h1>')
	
 	csv_data = a_request.POST.get('csv_text')
#  	assert False
# 	stripped_csv_data = (item.strip() for item in csv_data.split())
 	payments = PaymentCsvModel.import_data(csv_data.split('\r\n'))
	for csv_model in payments:
		corporation = Corporation.objects.get(cid=csv_model.corporation)
		assert corporation != None
		
		p = Payment(
			corporation=corporation, 
    		owner=a_request.user,
    		amount=csv_model.amount,
    		title=csv_model.title,
    		due_date=csv_model.due_date,
    		supply_date=csv_model.supply_date,
    		order_date=csv_model.order_date,
    		pay_date=csv_model.pay_date
		)
		
		p.save()
	return HttpResponseRedirect(reverse_lazy('payments',
        kwargs={'username': username})
    )
Exemplo n.º 2
0
    def test_can_set_as_paid_if_has_withdraw_address_internal(self):
        # Creates an withdraw address fro this user
        address = Address(user=self.user,
                          type='W',
                          address='17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j')
        address.save()

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

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

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

        # Set Order as Paid
        response = self.client.post(self.url, {'paid': 'true'})
        expected = {"frozen": True, "paid": True, "status": "OK"}
        self.assertJSONEqual(
            json.dumps(expected),
            str(response.content, encoding='utf8'),
        )
Exemplo n.º 3
0
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()
Exemplo n.º 4
0
    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()
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
    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())
Exemplo n.º 7
0
def payment(request, plan_type):
    user_email = request.user.email
    if request.method == 'POST':
        stripe_token = request.POST['stripeToken']
        logger.error(plan_type)
        customer = stripe.Customer.create(
            email = user_email,
            description = '{request.user.first_name} { request.user.last_name} - { user_email}',
            card = stripe_token,
            plan = plan_type
        )
        payment = Payment(
            user_id = request.user.id,
            stripe_id = customer.id,
            card_type = customer.active_card.type,
            card_digits = customer.active_card.last4,
            plan_type = plan_type,
            is_active = 1,
        )
        try:
            payment.save()
        except IntegrityError:
            messages.error(request, 'Your payment information could not be saved. #33') 
        else:
            messages.success(request, 'Payment information has been saved.') 
            return redirect('payments.views.index')
    
    return render_to_response(
            'payments/payment.html', 
            {
                'plan_type': plan_type,
                'publishable': settings.STRIPE_PUBLISHABLE,
                'sub_nav_path': 'partials/settings_sub_nav.html',
            },
            context_instance=RequestContext(request))
Exemplo n.º 8
0
 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
Exemplo n.º 9
0
def stripe_webhook(request):
    payload = request.body
    sig_header = request.META.get("HTTP_STRIPE_SIGNATURE")

    if not payload or not sig_header:
        return HttpResponse("[invalid payload]", status=400)

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
        )
    except ValueError:
        return HttpResponse("[invalid payload]", status=400)
    except stripe.error.SignatureVerificationError:
        return HttpResponse("[invalid signature]", status=400)

    log.info("Stripe webhook event: " + event["type"])

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        try:
            payment = Payment.finish(
                reference=session["id"],
                status=Payment.STATUS_SUCCESS,
                data=session,
            )
        except PaymentException:
            return HttpResponse("[payment not found]", status=400)

        product = PRODUCTS[payment.product_code]
        product["activator"](product, payment, payment.user)
        return HttpResponse("[ok]", status=200)

    if event["type"] == "invoice.paid":
        invoice = event["data"]["object"]
        if invoice["billing_reason"] == "subscription_create":
            # already processed in "checkout.session.completed" event
            return HttpResponse("[ok]", status=200)

        user = User.objects.filter(stripe_id=invoice["customer"]).first()
        # todo: do we need throw error in case user not found?

        payment = Payment.create(
            reference=invoice["id"],
            user=user,
            product=find_by_stripe_id(invoice["lines"]["data"][0]["plan"]["id"]),
            data=invoice,
            status=Payment.STATUS_SUCCESS,
        )
        product = PRODUCTS[payment.product_code]
        product["activator"](product, payment, user)
        return HttpResponse("[ok]", status=200)

    if event["type"] in {"customer.created", "customer.updated"}:
        customer = event["data"]["object"]
        User.objects.filter(email=customer["email"]).update(stripe_id=customer["id"])
        return HttpResponse("[ok]", status=200)

    return HttpResponse("[unknown event]", status=400)
Exemplo n.º 10
0
    def setUp(self):
        super(PaymentReleaseTestCase, self).setUp()
        self.method_data = {"is_internal": 1, 'name': 'Robokassa'}

        amount_cash = Decimal(30000.00)

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

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

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

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

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

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

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

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

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

        tx_id_ = '76aa6bdc27e0bb718806c93db66525436' \
                 'fa621766b52bad831942dee8b618678'

        self.transaction = Transaction(tx_id=tx_id_,
                                       order=self.order,
                                       address_to=self.addr)
        self.transaction.save()
    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)
Exemplo n.º 12
0
 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
Exemplo n.º 13
0
    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",
        )
Exemplo n.º 14
0
    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()
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
    def test_finish_payment_positive(self):
        result: Payment = Payment.finish(
            reference=self.existed_payment.reference,
            status=Payment.STATUS_SUCCESS,
            data={"some": "data"})

        self.assertIsNotNone(result)
        # check it persistent
        payment = Payment.get(reference=result.reference)
        self.assertIsNotNone(payment)
        self.assertEqual(payment.id, self.existed_payment.id)
        self.assertEqual(payment.status, Payment.STATUS_SUCCESS)
        self.assertEqual(payment.data, '{"some": "data"}')
Exemplo n.º 17
0
    def test_delete_payment(self):
        outcome = Payment.create_payment(drawee=self.user.username,
                                         pledger=self.user2.username,
                                         amount=-125.0,
                                         room="test_payment",
                                         name="test_payment")
        payment_id = outcome['payment'].id

        self.assertEqual(Payment.objects.count(), 1)

        Payment.delete_payment(payment_id)

        self.assertEqual(Payment.objects.count(), 0)
Exemplo n.º 18
0
def update_payment_status(ptype, task, request, data=None):
    data = data or {}
    status = co.IN_PROCESS
    if ptype == co.LIQPAY:
        from liqpay.liqpay import LiqPay
        liq = LiqPay(co.LIQ_PUB_KEY, co.LIQ_PRIV_KEY)
        liq = liq.api("payment/status", {"order_id": task.id})
        try:
            values = json.dumps(liq)
        except:
            values = '{}'
        if liq.get('result') == 'ok' and liq.get('status') in [
                'success', 'sandbox'
        ]:
            fraud = float(task.get_price()) - float(liq.get('amount',
                                                            0.00)) > 0.03
            status = co.PAID
            if fraud:
                status = co.UNDERPAID
    elif ptype == co.TWOCHECKOUT:
        import twocheckout
        # mode: production, mode:sandbox
        twocheckout.Api.auth_credentials({
            'private_key': co.TWO_PRIV_KEY,
            'seller_id': co.TWOSID
        })
        twocheckout.Api.credentials({
            'username': co.TWO_USERNAME,
            'password': co.TWO_PASSWORD
        })
        sale_id = data.get('sale_id')
        try:
            sale_status = twocheckout.Sale.find({'sale_id': sale_id
                                                 })['invoices'][0]['status']
            amount = twocheckout.Sale.find({'sale_id': sale_id
                                            })['invoices'][0]['usd_total']
        except (twocheckout.error.TwocheckoutError, KeyError, IndexError):
            return
        if sale_status in ['deposited']:
            fraud = float(task.get_price()) - float(amount) > 0.03
            status = co.PAID
            if fraud:
                status = co.UNDERPAID
            payment = Payment(powner=task.owner,
                              ptask=task,
                              values=json.dumps(data),
                              payment_status=status,
                              payment_type=ptype)
            payment.save()
Exemplo n.º 19
0
    def test_set_user_on_match(self, send_email, send_sms, release_payment):
        release_payment.return_value = 'A555B'
        self.payment = Payment(**self.base_payment_data)
        self.payment.save()

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

        wallet_release.apply()

        self.payment.refresh_from_db()

        # for easiness
        p = self.payment
        self.assertEqual(p.payment_preference.user, self.order.user)
        self.assertEquals(p.user, self.order.user, p.payment_preference.user)
Exemplo n.º 20
0
    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)
Exemplo n.º 21
0
    def test_event_checkout_session_completed_positive(self):
        # links:
        #   https://stripe.com/docs/webhooks/signatures
        #   https://stripe.com/docs/api/events/object

        # given
        product = PRODUCTS["club1"]
        opened_payment: Payment = Payment.create(reference=f"random-reference-{uuid.uuid4()}",
                                                 user=self.existed_user,
                                                 product=product)

        strip_secret = "stripe_secret"
        with self.settings(STRIPE_WEBHOOK_SECRET=strip_secret):
            json_event = self.read_json_event('checkout.session.completed')
            json_event['data']['object']['id'] = opened_payment.reference

            timestamp = int(time.time())
            signed_payload = f"{timestamp}.{json.dumps(json_event)}"
            computed_signature = WebhookSignature._compute_signature(signed_payload, strip_secret)

            # when
            header = {'HTTP_STRIPE_SIGNATURE': f't={timestamp},v1={computed_signature}'}
            response = self.client.post(reverse("stripe_webhook"), data=json_event,
                                        content_type='application/json', **header)

            # then
            self.assertEqual(response.status_code, 200)
            # subscription prolongated
            user = User.objects.get(id=self.existed_user.id)
            self.assertAlmostEquals(user.membership_expires_at,
                                    self.existed_user.membership_expires_at + product['data']['timedelta'],
                                    delta=timedelta(seconds=10))
Exemplo n.º 22
0
    def test_positive_new_user(self, mocked_stripe):
        # given
        product_code = "club1"
        email = f"new-user-{uuid.uuid4()}@email.com"
        StripeSession = namedtuple('Session', "id")
        session = StripeSession(id=f"{uuid.uuid4()}")
        mocked_stripe.checkout.Session.create.return_value = session

        # when
        response = self.client.get(reverse("pay"),
                                   data={
                                       "product_code": product_code,
                                       # "is_recurrent": PRODUCTS[product_code]["recurrent"],
                                       "email": email
                                   })

        # check
        self.assertTrue(User.objects.filter(email=email).exists(), )
        created_user: User = User.objects.get(email=email)
        self.assertEqual(created_user.email, email)
        self.assertEqual(created_user.membership_platform_type, User.MEMBERSHIP_PLATFORM_DIRECT)
        self.assertEqual(created_user.full_name, email.replace("@email.com", ""))
        self.assertAlmostEquals(created_user.membership_started_at, datetime.utcnow(), delta=timedelta(seconds=5))
        self.assertAlmostEquals(created_user.membership_expires_at, datetime.utcnow() + timedelta(days=1),
                                delta=timedelta(seconds=5))
        self.assertEqual(created_user.moderation_status, User.MODERATION_STATUS_INTRO)

        self.assertTrue(Payment.get(reference=session.id))
        self.assertContains(response=response, text="Платим 💰", status_code=200)
Exemplo n.º 23
0
    def test_positive_existed_authorised_user(self, mocked_stripe):
        # given
        product_code = "club1"
        StripeSession = namedtuple('Session', "id")
        session = StripeSession(id=f"{uuid.uuid4()}")
        mocked_stripe.checkout.Session.create.return_value = session
        self.client.authorise()

        # when
        response = self.client.get(reverse("pay"),
                                   data={
                                       "product_code": product_code,
                                   })

        # check
        self.assertTrue(
            User.objects.filter(email=self.existed_user.email).exists(), )
        user_after: User = User.objects.get(email=self.existed_user.email)
        self.assertEqual(user_after.membership_platform_type,
                         self.existed_user.membership_platform_type)
        self.assertEqual(user_after.full_name, self.existed_user.full_name)
        self.assertEqual(user_after.membership_started_at,
                         self.existed_user.membership_started_at)
        self.assertAlmostEquals(user_after.membership_expires_at,
                                self.existed_user.membership_expires_at)
        self.assertEqual(user_after.moderation_status,
                         self.existed_user.moderation_status)

        self.assertTrue(Payment.get(reference=session.id))
        self.assertContains(response=response,
                            text="Платим 💰",
                            status_code=200)
Exemplo n.º 24
0
def stripe_webhook(request):
    payload = request.body
    sig_header = request.META.get("HTTP_STRIPE_SIGNATURE")

    if not payload or not sig_header:
        return HttpResponse("[invalid payload]", status=400)

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
        )
    except ValueError:
        return HttpResponse("[invalid payload]", status=400)
    except stripe.error.SignatureVerificationError:
        return HttpResponse("[invalid signature]", status=400)

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        payment = Payment.finish(
            reference=session["id"],
            status=Payment.PAYMENT_STATUS_SUCCESS,
            data=session,
        )
        product = PRODUCTS[payment.product_code]
        product["activator"](product, payment, payment.user)

    return HttpResponse("[ok]", status=200)
Exemplo n.º 25
0
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
Exemplo n.º 26
0
    def test_club_subscription_activator_positive_membership_expires_in_future(
            self):
        # given
        future_membership_expiration = datetime.utcnow() + timedelta(days=5)
        existed_user: User = User.objects.create(
            email="*****@*****.**",
            membership_started_at=datetime.utcnow() - timedelta(days=5),
            membership_expires_at=future_membership_expiration,
        )
        new_payment: Payment = Payment.create(
            reference=f"random-reference-{uuid.uuid4()}",
            user=existed_user,
            product=PRODUCTS["club1"])

        # when
        result = products.club_subscription_activator(
            product=PRODUCTS["club1_recurrent_yearly"],
            payment=new_payment,
            user=existed_user)

        # then
        self.assertTrue(result)

        user = User.objects.get(id=existed_user.id)
        self.assertAlmostEquals(user.membership_expires_at,
                                future_membership_expiration +
                                timedelta(days=365),
                                delta=timedelta(seconds=10))
        self.assertEqual(user.membership_platform_type,
                         User.MEMBERSHIP_PLATFORM_DIRECT)
        self.assertEqual(user.membership_platform_data, {
            "reference": new_payment.reference,
            "recurrent": "yearly"
        })
Exemplo n.º 27
0
 def pay_for_the_order(self, **kwargs):
     error_msg = _('Something went wrong. Order is not paid.')
     success_msg = _('Order is paid successfully!')
     self.order = Order.objects.get(unique_reference=kwargs['orderid'])
     if self.validate_order(self.order, **kwargs):
         try:
             res = self.create_transaction(**kwargs)
         except KeyError as e:
             error_msg = _('Bad Credit Card credentials')
             return {'status': 0, 'msg': error_msg}
         if res['status'] == '1':
             # FIXME: CANCEL CARDPMT because it doesnt work
             self.order.cancel()
             self.order.refresh_from_db()
             if res['transaction_id'] == '0' or res['transaction_id'] is \
                     None:
                 error_msg = _('Order payment status is unclear, please '
                               'contact administrator!')
                 return {'status': 0, 'msg': error_msg}
             if not self.check_unique_transaction_id(res['transaction_id']):
                 return {'status': 0, 'msg': error_msg}
             # FIXME: CANCEL CARDPMT because it doesnt work
             self.order.cancel()
             self.order.refresh_from_db()
             pref = self.create_payment_preference(self.order, **kwargs)
             currency = Currency.objects.get(code=kwargs['currency'])
             payment = Payment(is_success=res['status'],
                               payment_system_id=res['transaction_id'],
                               reference=self.order.unique_reference,
                               amount_cash=kwargs['amount'],
                               payment_preference=pref,
                               order=self.order,
                               user=self.order.user if self.order else None,
                               currency=currency)
             payment.save()
             return {'status': 1, 'msg': success_msg}
         elif 'msg' in res:
             return res
         else:
             self.logger.error(
                 'Bad Payment status. response:{},order:{}'.format(
                     res, self.order))
             return {'status': 0, 'msg': error_msg}
     else:
         if self.order.status == Order.PAID:
             error_msg = _("This order is already paid")
         return {'status': 0, 'msg': error_msg}
Exemplo n.º 28
0
    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)
Exemplo n.º 29
0
    def test_delete_payment_integrity_check(self):
        outcome = Payment.create_payment(drawee=self.user.username,
                                         pledger=self.user2.username,
                                         amount=-125.0,
                                         room="test_payment",
                                         name="test_payment")

        matrix = Room.objects.get(name="test_payment").matrix

        self.assertEqual(matrix, '{"t_user":{"t_user":125.0,"t_user2":0.0},'
                                 '"t_user2":{"t_user":-125.0,"t_user2":0.0}}')

        Payment.delete_payment_keep_integrity(outcome['payment'].id)

        matrix = Room.objects.get(name="test_payment").matrix
        self.assertEqual(matrix, '{"t_user":{"t_user":0.0,"t_user2":0.0},'
                                 '"t_user2":{"t_user":0.0,"t_user2":0.0}}')
Exemplo n.º 30
0
    def test_get_payment_by_reference_positive(self):
        # when
        payment: Payment = Payment.get(
            reference=self.existed_payment.reference)

        # then
        self.assertIsNotNone(payment)
        self.assertEqual(payment.id, self.existed_payment.id)
Exemplo n.º 31
0
    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)
Exemplo n.º 32
0
    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)
Exemplo n.º 33
0
    def add_payment(self, payment):
        member = self.detect_member(payment)

        new_payment = Payment(
            date=payment.arrival,
            amount=payment.amount,
            payment_type=payment.payment_type,
            constant_symbol=payment.ks,
            variable_symbol=payment.vs,
            specific_symbol=payment.ss,
            identification=payment.identification,
            message=payment.message)

        if member:
            print('new payment (%s) from %s [%.2f]' % (payment.arrival,
                member, payment.amount))
            new_payment.user = member
        else:
            print('new payment (%s) - %s - %s [%.2f]'% (payment.arrival,
                payment.payment_type, payment.identification, payment.amount))

        new_payment.save()
Exemplo n.º 34
0
    def add_payment(self, payment):
        member = self.detect_member(payment)

        new_payment = Payment(
            date=payment['date'],
            amount=payment['amount'],
            payment_type=payment['type'],
            constant_symbol=payment['constant_symbol'],
            variable_symbol=payment['variable_symbol'],
            specific_symbol=payment['specific_symbol'],
            identification=payment['identification'],
            message=payment['recipient_message'])

        if member:
            print('new payment (%s) from %s [%.2f]' % (payment['date'],
                member, payment['amount']))
            new_payment.user = member
        else:
            print('new payment (%s) - %s - %s [%.2f]'% (payment['date'],
                payment['type'], payment['identification'], payment['amount']))

        new_payment.save()
Exemplo n.º 35
0
def corp_memb_inv_add(user, corp_memb, **kwargs): 
    """
    Add an invoice for this corporate membership
    """
    renewal = kwargs.get('renewal', False)
    renewal_total = kwargs.get('renewal_total', 0)
    renew_entry = kwargs.get('renew_entry', None)
    if not corp_memb.invoice or renewal:
        inv = Invoice()
        if renew_entry:
            inv.object_type = ContentType.objects.get(app_label=renew_entry._meta.app_label, 
                                                      model=renew_entry._meta.module_name)
            inv.object_id = renew_entry.id
        else:
            inv.object_type = ContentType.objects.get(app_label=corp_memb._meta.app_label, 
                                                      model=corp_memb._meta.module_name)
            inv.object_id = corp_memb.id
        inv.title = "Corporate Membership Invoice"
        inv.bill_to = corp_memb.name
        inv.bill_to_company = corp_memb.name
        inv.bill_to_address = corp_memb.address
        inv.bill_to_city = corp_memb.city
        inv.bill_to_state = corp_memb.state
        inv.bill_to_zip_code = corp_memb.zip
        inv.bill_to_country = corp_memb.country
        inv.bill_to_phone = corp_memb.phone
        inv.bill_to_email = corp_memb.email
        inv.ship_to = corp_memb.name
        inv.ship_to_company = corp_memb.name
        inv.ship_to_address = corp_memb.address
        inv.ship_to_city = corp_memb.city
        inv.ship_to_state = corp_memb.state
        inv.ship_to_zip_code = corp_memb.zip
        inv.ship_to_country = corp_memb.country
        inv.ship_to_phone = corp_memb.phone
        inv.ship_to_email =corp_memb.email
        inv.terms = "Due on Receipt"
        inv.due_date = datetime.now()
        inv.ship_date = datetime.now()
        inv.message = 'Thank You.'
        inv.status = True
        
        if not renewal:
            inv.total = corp_memb.corporate_membership_type.price
        else:
            inv.total = renewal_total
        inv.subtotal = inv.total
        inv.balance = inv.total
        inv.estimate = 1
        inv.status_detail = 'estimate'
        inv.save(user)


        if is_admin(user):
            # if offline payment method
            if not corp_memb.get_payment_method().is_online:
                inv.tender(user) # tendered the invoice for admin if offline

                # mark payment as made
                payment = Payment()
                payment.payments_pop_by_invoice_user(user, inv, inv.guid)
                payment.mark_as_paid()
                payment.method = corp_memb.get_payment_method()
                payment.save(user)

                # this will make accounting entry
                inv.make_payment(user, payment.amount)
        return inv
    return None
Exemplo n.º 36
0
def directory_set_inv_payment(user, directory, **kwargs): 
    if get_setting('module', 'directories', 'directoriesrequirespayment'):
        if not directory.invoice:
            inv = Invoice()
            inv.object_type = ContentType.objects.get(app_label=directory._meta.app_label, 
                                              model=directory._meta.module_name)
            inv.object_id = directory.id
            profile = user.get_profile()
            inv.title = "Directory Add Invoice"
            inv.bill_to = '%s %s' % (user.first_name, user.last_name)
            inv.bill_to_first_name = user.first_name
            inv.bill_to_last_name = user.last_name
            inv.bill_to_company = profile.company
            inv.bill_to_address = profile.address
            inv.bill_to_city = profile.city
            inv.bill_to_state = profile.state
            inv.bill_to_zip_code = profile.zipcode
            inv.bill_to_country = profile.country
            inv.bill_to_phone = profile.phone
            inv.bill_to_fax = profile.fax
            inv.bill_to_email = profile.email
            inv.ship_to = inv.bill_to
            inv.ship_to_first_name = user.first_name
            inv.ship_to_last_name = user.last_name
            inv.ship_to_company = profile.company
            inv.ship_to_address = profile.address
            inv.ship_to_city = profile.city
            inv.ship_to_state = profile.state
            inv.ship_to_zip_code = profile.zipcode
            inv.ship_to_country = profile.country
            inv.ship_to_phone = profile.phone
            inv.ship_to_fax = profile.fax
            inv.ship_to_email = profile.email
            inv.terms = "Due on Receipt"
            inv.due_date = datetime.now()
            inv.ship_date = datetime.now()
            inv.message = 'Thank You.'
            inv.status = True
            
            inv.total = get_directory_price(user, directory)
            inv.subtotal = inv.total
            inv.balance = inv.total
            inv.estimate = 1
            inv.status_detail = 'estimate'
            inv.save(user)
            
            # update job
            directory.invoice = inv
            directory.save()
            
            if is_admin(user):
                if directory.payment_method in ['paid - cc', 'paid - check', 'paid - wire transfer']:
                    boo_inv = inv.tender(user) 
                    
                    # payment
                    payment = Payment()
                    boo = payment.payments_pop_by_invoice_user(user, inv, inv.guid)
                    payment.mark_as_paid()
                    payment.method = directory.payment_method
                    payment.save(user)
                    
                    # this will make accounting entry
                    inv.make_payment(user, payment.amount)
Exemplo n.º 37
0
    p.accepted = True
    p.save()

    pid_map[int(m[0])] = u

def fix(inp):
    if inp==u'': return 0
    return int(inp)

def fixfloat(inp):
    if type(inp) == float:
        return inp
    return float(inp)

for p in ps:
    user = None
    if fix(p[5]) in pid_map:
        user = pid_map[fix(p[5])]

    p = Payment(
        date=date(*map(int, p[1].split('-'))),
        amount=fixfloat(p[2]),
        payment_type=p[3],
        constant_symbol=fix(p[4]),
        variable_symbol=fix(p[5]),
        specific_symbol=fix(p[6]),
        identification=p[7],
        message=p[8],
        user=user)
    p.save()
Exemplo n.º 38
0
def job_set_inv_payment(user, job, pricing):
    if get_setting('module', 'jobs', 'jobsrequirespayment'):
        if not job.invoice:
            inv = Invoice()
            inv.object_type = ContentType.objects.get(app_label=job._meta.app_label, 
                                              model=job._meta.module_name)
            inv.object_id = job.id
            inv.title = "Job Add Invoice"
            inv.bill_to = job.contact_name
            first_name = ''
            last_name = ''
            if job.contact_name:
                name_list = job.contact_name.split(' ')
                if len(name_list) >= 2:
                    first_name = name_list[0]
                    last_name = ' '.join(name_list[1:])
            inv.bill_to_first_name = first_name
            inv.bill_to_last_name = last_name
            inv.bill_to_company = job.contact_company
            inv.bill_to_address = job.contact_address
            inv.bill_to_city = job.contact_city
            inv.bill_to_state = job.contact_state
            inv.bill_to_zip_code = job.contact_zip_code
            inv.bill_to_country = job.contact_country
            inv.bill_to_phone = job.contact_phone
            inv.bill_to_fax = job.contact_fax
            inv.bill_to_email = job.contact_email
            inv.ship_to = job.contact_name
            inv.ship_to_first_name = first_name
            inv.ship_to_last_name = last_name
            inv.ship_to_company = job.contact_company
            inv.ship_to_address = job.contact_address
            inv.ship_to_city = job.contact_city
            inv.ship_to_state = job.contact_state
            inv.ship_to_zip_code = job.contact_zip_code
            inv.ship_to_country = job.contact_country
            inv.ship_to_phone = job.contact_phone
            inv.ship_to_fax = job.contact_fax
            inv.ship_to_email =job.contact_email
            inv.terms = "Due on Receipt"
            inv.due_date = datetime.now()
            inv.ship_date = datetime.now()
            inv.message = 'Thank You.'
            inv.status = True
            
            inv.total = get_job_price(user, job, pricing)
            inv.subtotal = inv.total
            inv.balance = inv.total
            inv.estimate = 1
            inv.status_detail = 'estimate'
            inv.save(user)
            
            # update job
            job.invoice = inv
            job.save()
            
            if is_admin(user):
                if job.payment_method in ['paid - cc', 'paid - check', 'paid - wire transfer']:
                    boo_inv = inv.tender(user) 
                    
                    # payment
                    payment = Payment()
                    boo = payment.payments_pop_by_invoice_user(user, inv, inv.guid)
                    payment.mark_as_paid()
                    payment.method = job.payment_method
                    payment.save(user)
                    
                    # this will make accounting entry
                    inv.make_payment(user, payment.amount)
Exemplo n.º 39
0
def pay_online(request, invoice_id, guid="", template_name="payments/pay_online.html"):
    # check if they have the right to view the invoice
    invoice = get_object_or_404(Invoice, pk=invoice_id)
    if not invoice.allow_view_by(request.user, guid): raise Http403
    
    # tender the invoice
    if not invoice.is_tendered:
        invoice.tender(request.user)
        # log an event for invoice edit
        log_defaults = {
            'event_id' : 312000,
            'event_data': '%s (%d) edited by %s' % (invoice._meta.object_name, invoice.pk, request.user),
            'description': '%s edited' % invoice._meta.object_name,
            'user': request.user,
            'request': request,
            'instance': invoice,
        }
        EventLog.objects.log(**log_defaults)  
      
    # generate the payment
    payment = Payment()
    
    boo = payment.payments_pop_by_invoice_user(request.user, invoice, guid)
    # log an event for payment add
    log_defaults = {
        'event_id' : 281000,
        'event_data': '%s (%d) added by %s' % (payment._meta.object_name, payment.pk, request.user),
        'description': '%s added' % payment._meta.object_name,
        'user': request.user,
        'request': request,
        'instance': payment,
    }
    EventLog.objects.log(**log_defaults)
    
    # post payment form to gateway and redirect to the vendor so customer can pay from there
    if boo:
        merchant_account = (get_setting("site", "global", "merchantaccount")).lower()
        
        if merchant_account == 'stripe':
            return HttpResponseRedirect(reverse('stripe.payonline', args=[payment.id]))    
        else:

            if merchant_account == "authorizenet":
                form = prepare_authorizenet_sim_form(request, payment)
                post_url = settings.AUTHNET_POST_URL
            elif merchant_account == 'firstdata':
                from payments.firstdata.utils import prepare_firstdata_form
                form = prepare_firstdata_form(request, payment)
                post_url = settings.FIRSTDATA_POST_URL
            elif merchant_account == 'paypalpayflowlink':
                from payments.payflowlink.utils import prepare_payflowlink_form
                form = prepare_payflowlink_form(request, payment)
                post_url = settings.PAYFLOWLINK_POST_URL
            else:   # more vendors 
                form = None
                post_url = ""
    else:
        form = None
        post_url = ""
    return render_to_response(template_name, 
                              {'form':form, 'post_url':post_url}, 
                              context_instance=RequestContext(request))