def test_generate_sticker_number_for_ws_lease(provider_base_config, order: Order): create_ws_sticker_sequences() order.status = OrderStatus.OFFERED order.order_number = "abc123" order.save() application = order.lease.application application.area_type = ApplicationAreaType.UNMARKED application.save() rf = RequestFactory() request = rf.get("/payments/success/", success_params) payment_provider = create_bambora_provider(provider_base_config, request) returned = payment_provider.handle_success_request() order_after = Order.objects.get( order_number=success_params.get("ORDER_NUMBER").split("-")[0]) assert order_after.status == OrderStatus.PAID assert order_after.lease.application.status == ApplicationStatus.HANDLED assert order_after.lease.sticker_number == 1 assert isinstance(returned, HttpResponse) url = returned.url assert "/payment-result" in url assert "payment_status=success" in url
def test_handle_notify_request_success( provider_base_config, order: Order, ): """Test request notify helper returns http 204 and order status is correct when successful""" order.order_number = "abc123" order.status = OrderStatus.PAID order.lease.status = LeaseStatus.PAID order.lease.save() order.save() refund = OrderRefundFactory( order=order, refund_id="1234567", amount=order.total_price ) rf = RequestFactory() request = rf.get("/payments/notify_refund/", notify_success_params) payment_provider = create_bambora_provider(provider_base_config, request) assert refund.status == OrderRefundStatus.PENDING returned = payment_provider.handle_notify_refund_request() refund = OrderRefund.objects.get(refund_id=notify_success_params.get("REFUND_ID")) order = refund.order assert refund.status == OrderRefundStatus.ACCEPTED assert order.status == OrderStatus.REFUNDED assert order.lease.status == LeaseStatus.TERMINATED assert isinstance(returned, HttpResponse) assert returned.status_code == 204
def test_fulfill_contract(superuser_api_client, order: Order): order.lease.contract.save() order.order_number = FULFILL_CONTRACT_MUTATION_INPUT["orderNumber"] order.save() executed = superuser_api_client.execute( FULFILL_CONTRACT_MUTATION, input=FULFILL_CONTRACT_MUTATION_INPUT) assert (executed["data"]["fulfillContract"]["signingUrl"] == TestContractService.signing_url)
def test_fulfill_contract_no_contract_for_order(superuser_api_client, order: Order): order.lease.contract = None order.lease.save() order.order_number = FULFILL_CONTRACT_MUTATION_INPUT["orderNumber"] order.save() executed = superuser_api_client.execute( FULFILL_CONTRACT_MUTATION, input=FULFILL_CONTRACT_MUTATION_INPUT) assert_in_errors("No contract found for given order", executed)
def test_initiate_refund_no_order_email(provider_base_config: dict, order: Order): """Test the request creator constructs the payload base and returns a url that contains a token""" request = RequestFactory().request() order.status = OrderStatus.PAID order.email = None order.lease.status = LeaseStatus.PAID order.lease.save() order.save() OrderToken.objects.create( order=order, token="12345", valid_until=now() - relativedelta(days=7) ) if hasattr(order.product, "price_for_tier"): place_price = order.product.price_for_tier(order.lease.berth.pier.price_tier) area = order.lease.berth.pier.harbor else: # Winter products are priced per m2 place_price = rounded( order.product.price_value * order.lease.place.place_type.width * order.lease.place.place_type.length, round_to_nearest=1, ) area = order.lease.place.winter_storage_section.area products = [ { "id": get_talpa_product_id(order.product.id, area, False), "product_id": 1123, "title": order.product.name, "count": 1, "pretax_price": price_as_fractional_int( convert_aftertax_to_pretax(place_price, order.product.tax_percentage) ), "tax": int(order.product.tax_percentage), "price": price_as_fractional_int(place_price), "type": 1, } ] payment_provider = create_bambora_provider(provider_base_config, request) with mock.patch( "payments.providers.bambora_payform.requests.post", side_effect=mocked_refund_response_create, ), mock.patch( "payments.providers.bambora_payform.BamboraPayformProvider.get_payment_details", side_effect=mocked_refund_payment_details(products=products), ): refund = payment_provider.initiate_refund(order) assert refund.refund_id == "123456"
def test_initiate_refund_refunded_amount_does_not_match( provider_base_config: dict, order: Order ): """Test the request creator constructs the payload base and returns a url that contains a token""" request = RequestFactory().request() order.status = OrderStatus.PAID order.lease.status = LeaseStatus.PAID order.lease.save() order.save() OrderToken.objects.create( order=order, token="98765", valid_until=now() - relativedelta(hours=1) ) OrderToken.objects.create( order=order, token="12345", valid_until=now() - relativedelta(days=7) ) place_price = order.total_price + 10 products = [ { "id": "123123123", "product_id": 1123, "title": order.product.name, "count": 1, "pretax_price": price_as_fractional_int( convert_aftertax_to_pretax(place_price, order.product.tax_percentage) ), "tax": int(order.product.tax_percentage), "price": price_as_fractional_int(place_price), "type": 1, } ] payment_provider = create_bambora_provider(provider_base_config, request) with mock.patch( "payments.providers.bambora_payform.requests.post", side_effect=mocked_refund_response_create, ), mock.patch( "payments.providers.bambora_payform.BamboraPayformProvider.get_payment_details", side_effect=mocked_refund_payment_details(products=products), ), pytest.raises( RefundPriceError ) as exception: payment_provider.initiate_refund(order) assert ( f"The amount to be refunded ({currency_format(place_price)}) " f"does not match the amount paid ({currency_format(order.total_price)})" ) in str(exception) assert not OrderRefund.objects.exists()
def test_approve_order_with_non_billable_customer( order: Order, helsinki_profile_user, ): order.status = OrderStatus.DRAFTED order.save(update_fields=["status"]) request = RequestFactory().request() due_date = today().date() approve_order(order, "", due_date, helsinki_profile_user, request) order.refresh_from_db() assert order.status == OrderStatus.PAID_MANUALLY assert len(mail.outbox) == 0
def save_order(order_entity): order = Order(order_id=order_entity['id']) order.amount = order_entity['amount'] order.currency = order_entity['currency'] order.status = order_entity['status'] order.created_at = str(order_entity['created_at']) order.save()
def test_payload_add_customer_success(payment_provider, order_with_products: Order): """Test the customer data from order is added correctly into payload""" # it should not use this value if application is present order_with_products.customer_first_name = "first_name" payload = {} payment_provider.payload_add_customer(payload, order_with_products) assert "email" in payload assert payload.get("email") == order_with_products.lease.application.email assert "customer" in payload customer = payload.get("customer") assert (customer.get("firstname") == order_with_products.lease.application.first_name.capitalize()) assert (customer.get("lastname") == order_with_products.lease.application.last_name.capitalize()) assert customer.get("email") == order_with_products.lease.application.email assert (customer.get("address_street") == order_with_products.lease.application.address) assert customer.get( "address_zip") == order_with_products.lease.application.zip_code assert (customer.get("address_city") == order_with_products.lease.application.municipality.capitalize())
def test_send_payment_notification_example_email(order: Order): order.customer_email = "*****@*****.**" with pytest.raises(ValidationError) as exception: send_payment_notification(order, RequestFactory().request()) assert "Missing customer email" in str(exception)
def test_initiate_refund_another_pending_refund( provider_base_config: dict, order: Order ): """Test the request creator constructs the payload base and returns a url that contains a token""" request = RequestFactory().request() order.status = OrderStatus.PAID order.lease.status = LeaseStatus.PAID order.lease.save() order.save() OrderRefundFactory(order=order, status=OrderRefundStatus.PENDING) OrderToken.objects.create( order=order, token="98765", valid_until=now() - relativedelta(hours=1) ) OrderToken.objects.create( order=order, token="12345", valid_until=now() - relativedelta(days=7) ) products = [ { "id": "123123123", "product_id": 1123, "title": order.product.name, "count": 1, "pretax_price": 100, "tax": 24, "price": 100, "type": 1, } ] assert OrderRefund.objects.count() == 1 payment_provider = create_bambora_provider(provider_base_config, request) with mock.patch( "payments.providers.bambora_payform.requests.post", side_effect=mocked_refund_response_create, ), mock.patch( "payments.providers.bambora_payform.BamboraPayformProvider.get_payment_details", side_effect=mocked_refund_payment_details(products=products), ), pytest.raises( ValidationError ) as exception: payment_provider.initiate_refund(order) assert "Cannot refund an order that has another pending refund" in str(exception) assert OrderRefund.objects.count() == 1
def test_initiate_refund_invalid_order_status( provider_base_config: dict, order: Order, order_status ): """Test the request creator constructs the payload base and returns a url that contains a token""" request = RequestFactory().request() order.status = order_status order.save() OrderToken.objects.create( order=order, token="98765", valid_until=now() - relativedelta(hours=1) ) OrderToken.objects.create( order=order, token="12345", valid_until=now() - relativedelta(days=7) ) payment_provider = create_bambora_provider(provider_base_config, request) with pytest.raises(ValidationError) as exception: payment_provider.initiate_refund(order) assert "Cannot refund an order that is not paid" in str(exception)
def test_handle_notify_request_success( provider_base_config, berth_order: Order, order_status: OrderStatus, expected_order_status: OrderStatus, ): """Test request notify helper returns http 204 and order status is correct when successful""" berth_order.order_number = "abc123" berth_order.status = order_status berth_order.save() rf = RequestFactory() request = rf.get("/payments/notify/", success_params) payment_provider = create_bambora_provider(provider_base_config, request) returned = payment_provider.handle_notify_request() order_after = Order.objects.get( order_number=success_params.get("ORDER_NUMBER").split("-")[0]) assert order_after.status == expected_order_status assert isinstance(returned, HttpResponse) assert returned.status_code == 204
def test_initiate_refund_no_order_email_or_application( provider_base_config: dict, order: Order ): """Test the request creator constructs the payload base and returns a url that contains a token""" request = RequestFactory().request() order.status = OrderStatus.PAID order.customer_email = None order.lease.status = LeaseStatus.PAID order.lease.application = None order.lease.save() order.save() OrderToken.objects.create( order=order, token="12345", valid_until=now() - relativedelta(days=7) ) payment_provider = create_bambora_provider(provider_base_config, request) with pytest.raises(ValidationError) as exception: payment_provider.initiate_refund(order) assert "Cannot refund an order that has no email" in str(exception)
def test_payload_add_customer_no_application(payment_provider, berth_order: Order): berth_order.customer_email = "*****@*****.**" berth_order.customer_first_name = "Matti" berth_order.customer_last_name = "Virtanen" berth_order.customer_address = "Street 1" berth_order.customer_zip_code = "33100" berth_order.customer_city = "Tampere" berth_order.lease.application = None payload = {} payment_provider.payload_add_customer(payload, berth_order) assert payload.get("email") == berth_order.customer_email customer = payload.get("customer") assert customer.get( "firstname") == berth_order.customer_first_name.capitalize() assert customer.get( "lastname") == berth_order.customer_last_name.capitalize() assert customer.get("email") == berth_order.customer_email assert customer.get("address_street") == berth_order.customer_address assert customer.get("address_zip") == berth_order.customer_zip_code assert customer.get( "address_city") == berth_order.customer_city.capitalize()
def test_handle_notify_request_success_for_ap_order( provider_base_config, berth_order: Order, ): berth_order.order_number = "abc123" berth_order.status = OrderStatus.OFFERED berth_order.order_type = OrderType.ADDITIONAL_PRODUCT_ORDER berth_order.save() rf = RequestFactory() request = rf.get("/payments/notify/", success_params) payment_provider = create_bambora_provider(provider_base_config, request) returned = payment_provider.handle_notify_request() order_after = Order.objects.get( order_number=success_params.get("ORDER_NUMBER").split("-")[0]) assert order_after.status == OrderStatus.PAID # it should not change the application and lease status in case of additional product order assert order_after.lease.application.status == ApplicationStatus.PENDING assert order_after.lease.status == LeaseStatus.DRAFTED assert isinstance(returned, HttpResponse) assert returned.status_code == 204
def test_approve_order( order: Order, payment_provider, notification_template_orders_approved, helsinki_profile_user, ): order.status = OrderStatus.DRAFTED order.save(update_fields=["status"]) request = RequestFactory().request() due_date = today().date() approve_order(order, order.lease.application.email, due_date, helsinki_profile_user, request) order.refresh_from_db() assert order.due_date == due_date assert order.lease.status == LeaseStatus.OFFERED assert order.lease.application.status == ApplicationStatus.OFFER_SENT assert order.customer_first_name == helsinki_profile_user.first_name assert order.customer_last_name == helsinki_profile_user.last_name assert order.customer_email == helsinki_profile_user.email assert order.customer_address == helsinki_profile_user.address assert order.customer_zip_code == helsinki_profile_user.postal_code assert order.customer_city == helsinki_profile_user.city payment_url = payment_provider.get_payment_email_url( order, lang=order.lease.application.language) assert len(mail.outbox) == 1 assert (mail.outbox[0].subject == f"test order approved subject, event: {order.order_number}!") assert mail.outbox[0].body == f"{ order.order_number } { payment_url }" assert mail.outbox[0].to == [order.lease.application.email] assert mail.outbox[0].alternatives == [ (f"<b>{ order.order_number } { payment_url }</b>", "text/html") ]
def test_handle_success_request_success(provider_base_config, order: Order): """Test request helper changes the order status to PAID Also check it returns a success url with order number""" order.status = OrderStatus.OFFERED order.order_number = "abc123" order.save() rf = RequestFactory() request = rf.get("/payments/success/", success_params) payment_provider = create_bambora_provider(provider_base_config, request) returned = payment_provider.handle_success_request() order_after = Order.objects.get( order_number=success_params.get("ORDER_NUMBER").split("-")[0]) assert order_after.status == OrderStatus.PAID assert order_after.lease.application.status == ApplicationStatus.HANDLED assert isinstance(returned, HttpResponse) url = returned.url assert "/payment-result" in url assert "payment_status=success" in url
def save(self, *args, **kwargs): if not self.pk: super(Visit, self).save(*args, **kwargs) from payments.models import Order if getattr(self, 'shift', False) and self.shift.shift_type.doctor.is_private: order = Order(interaction=self) order.save() else: super(Visit, self).save(*args, **kwargs) for order in self.orders.all(): order.save()
def fail_order(self, order: Order, message: str, dont_count: bool = False) -> None: """Set an order to ERROR status and append it to the failed_order list""" order.set_status(OrderStatus.ERROR, f"Lease renewing failed: {message}") order.comment = f"{get_ts()}: {message}" order.due_date = None order.save(update_fields=["comment", "due_date"]) self.failed_orders.append({order.id: message}) self.failure_count += 1 if not dont_count else 0 logger.debug(f"Lease order [{order.id}]: {message}")
def post(self, request, *args, **kwargs): movie_id = request.data.get("movie_id") movie = get_object_or_404(Movie, pk=movie_id) movie_home_url = f"https://{ settings.ALLOWED_HOSTS[0]}/movie/{movie_id}/" order = Order.objects.filter(movie_id=movie_id, user=self.request.user).first() if order is None: order = Order(movie_id=movie_id, user=self.request.user) if order.completed: return Response(JSONRenderer().render( {"detail": "Already Bought."})) try: checkout_session = stripe.checkout.Session.create( payment_method_types=["card"], line_items=[ { "price_data": { "currency": "usd", "unit_amount_decimal": movie.price * 100, "product_data": { "name": movie.title, "images": [ f"https://{settings.ALLOWED_HOSTS[0]}{movie.poster_image.url}", ], }, }, "quantity": 1, }, ], mode="payment", success_url=movie_home_url + "?success=true", cancel_url=movie_home_url + "?canceled=true", ) order.price = movie.price order.session_id = checkout_session.id order.save() return Response(JSONRenderer().render({"id": checkout_session.id})) except Exception as e: return Response( JSONRenderer().render({"error": str(e.http_body)}), status=e.http_status, )
def test_duplicate_payments_tokens_cancelled_notify_payment( provider_base_config, order: Order): # Fake the Payment initiate flow order.status = OrderStatus.OFFERED order.order_number = "abc123" order.save() request = RequestFactory().request() payment_provider = create_bambora_provider(provider_base_config, request) assert OrderToken.objects.count() == 0 with mock.patch( "payments.providers.bambora_payform.requests.post", side_effect=mocked_response_create, ) as mock_call: payment_provider.initiate_payment(order) assert OrderToken.objects.count() == 1 token = OrderToken.objects.first() assert token.order == order assert token.valid_until.isoformat( ) == "2019-01-20T21:59:59.999999+00:00" # Try to pay again 7 days after the day when the payment was created with freeze_time("2019-01-21T08:00:00Z"): url = payment_provider.initiate_payment(order) # Verify that the return URL passed includes the application language assert order.lease.application.language in mock_call.call_args.kwargs.get( "json").get("payment_method").get("return_url") assert OrderToken.objects.count() == 2 assert url.startswith(payment_provider.url_payment_api) assert "token/token123" in url # Fake the part where Bambora notifies the success/failure params = { "VENE_UI_RETURN_URL": "http%3A%2F%2F127.0.0.1%3A8000%2Fv1", "AUTHCODE": "DD789BA71ACD627892517745AF4C4CE2068F006C602CD54264E1FC5E4C2EE6CF", "RETURN_CODE": "1", "ORDER_NUMBER": "abc123-1602145394.662132", } rf = RequestFactory() request = rf.get("/payments/success/", params) payment_provider = create_bambora_provider(provider_base_config, request) payment_provider.handle_notify_request() order_after = Order.objects.get( order_number=params.get("ORDER_NUMBER").split("-")[0]) assert all([token.cancelled for token in order_after.tokens.all()]) with mock.patch( "payments.providers.bambora_payform.requests.post", side_effect=mocked_response_create, ): with freeze_time("2019-01-31T08:00:00Z"): payment_provider.initiate_payment(order) # The last token shouldn't be cancelled assert OrderToken.objects.count() == 3 assert OrderToken.objects.filter(cancelled=True).count() == 2 assert OrderToken.objects.filter(cancelled=False).count() == 1