Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Extend order payload with undiscounted prices and add `psp_reference` to payment model (#7339)

Iga Karbowiak040a5810ce95
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d2d47f6f92..8008952678 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,16 @@ All notable, unreleased changes to this project will be documented in this file.
- Raise ValidationError when refund cannot be performed - #7260 by @IKarbowiak
- Extend order with origin and original order values - #7326 by @IKarbowiak
- Fix customer addresses missing after customer creation - #7327 by @tomaszszymanski129
+- Extend order payload with undiscounted prices and add psp_reference to payment model - #7339 by @IKarbowiak
+ - order payload extended with the following fields:
+ - `undiscounted_total_net_amount`
+ - `undiscounted_total_gross_amount`
+ - `psp_reference` on `payment`
+ - order lines extended with:
+ - `undiscounted_unit_price_net_amount`
+ - `undiscounted_unit_price_gross_amount`
+ - `undiscounted_total_price_net_amount`
+ - `undiscounted_total_price_gross_amount`
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index aecdc2cc65..3a769e3997 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -602,6 +602,8 @@ def create_order_lines(order, discounts, how_many=10):
variant=variant,
unit_price=unit_price,
total_price=total_price,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=total_price,
tax_rate=0,
)
)
@@ -617,13 +619,28 @@ def create_order_lines(order, discounts, how_many=10):
unit_price = manager.calculate_order_line_unit(
order, line, variant, variant.product
)
+ total_price = manager.calculate_order_line_total(
+ order, line, variant, variant.product
+ )
line.unit_price = unit_price
+ line.total_price = total_price
+ line.undiscounted_unit_price = unit_price
+ line.undiscounted_total_price = total_price
line.tax_rate = unit_price.tax / unit_price.net
warehouse = next(warehouse_iter)
increase_stock(line, warehouse, line.quantity, allocate=True)
OrderLine.objects.bulk_update(
lines,
- ["unit_price_net_amount", "unit_price_gross_amount", "currency", "tax_rate"],
+ [
+ "unit_price_net_amount",
+ "unit_price_gross_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
+ "currency",
+ "tax_rate",
+ ],
)
return lines
diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.py
index 90a6193410..3fc0847db9 100644
--- a/saleor/graphql/order/filters.py
+++ b/saleor/graphql/order/filters.py
@@ -4,7 +4,7 @@ from graphene_django.filter import GlobalIDMultipleChoiceFilter
from ...discount.models import OrderDiscount
from ...order.models import Order
-from ...payment.models import Payment, Transaction
+from ...payment.models import Payment
from ..channel.types import Channel
from ..core.filters import ListObjectTypeFilter, MetadataFilterBase, ObjectTypeFilter
from ..core.types.common import DateRangeInput
@@ -79,10 +79,7 @@ def filter_order_search(qs, _, value):
if order_id := get_order_id_from_query(value):
return qs.filter(pk=order_id)
- transactions = Transaction.objects.filter(searchable_key=value).values("id")
- payments = Payment.objects.filter(
- Exists(transactions.filter(payment_id=OuterRef("id")))
- ).values("id")
+ payments = Payment.objects.filter(psp_reference=value).values("id")
discounts = OrderDiscount.objects.filter(
Q(name__trigram_similar=value) | Q(translated_name__trigram_similar=value)
).values("id")
diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.py
index 95f4833343..255b38b5f0 100644
--- a/saleor/graphql/order/tests/test_discount_order.py
+++ b/saleor/graphql/order/tests/test_discount_order.py
@@ -500,6 +500,10 @@ def test_update_order_line_discount(
line_to_discount = order.lines.first()
unit_price = Money(Decimal(7.3), currency="USD")
line_to_discount.unit_price = TaxedMoney(unit_price, unit_price)
+ line_to_discount.undiscounted_unit_price = line_to_discount.unit_price
+ total_price = line_to_discount.unit_price * line_to_discount.quantity
+ line_to_discount.total_price = total_price
+ line_to_discount.undiscounted_total_price = total_price
line_to_discount.save()
line_price_before_discount = line_to_discount.unit_price
@@ -566,6 +570,19 @@ def test_update_order_line_discount_line_with_discount(
line_to_discount.unit_discount_amount = Decimal("2.500")
line_to_discount.unit_discount_type = DiscountValueType.FIXED
line_to_discount.unit_discount_value = Decimal("2.500")
+ line_to_discount.undiscounted_unit_price_gross_amount = (
+ line_to_discount.unit_price_gross_amount + line_to_discount.unit_discount_amount
+ )
+ line_to_discount.undiscounted_unit_price_net_amount = (
+ line_to_discount.unit_price_net_amount + line_to_discount.unit_discount_amount
+ )
+ line_to_discount.undiscounted_total_price_gross_amount = (
+ line_to_discount.undiscounted_unit_price_gross_amount
+ * line_to_discount.quantity
+ )
+ line_to_discount.undiscounted_total_price_net_amount = (
+ line_to_discount.undiscounted_unit_price_net_amount * line_to_discount.quantity
+ )
line_to_discount.save()
line_discount_amount_before_update = line_to_discount.unit_discount_amount
@@ -674,7 +691,9 @@ mutation OrderLineDiscountRemove($orderLineId: ID!){
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")
+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
def test_delete_discount_from_order_line(
+ mocked_calculate_order_line_total,
mocked_calculate_order_line_unit,
status,
draft_order_with_fixed_discount_order,
@@ -687,8 +706,10 @@ def test_delete_discount_from_order_line(
line = order.lines.first()
line_undiscounted_price = line.undiscounted_unit_price
+ line_undiscounted_total_price = line.undiscounted_total_price
mocked_calculate_order_line_unit.return_value = line_undiscounted_price
+ mocked_calculate_order_line_total.return_value = line_undiscounted_total_price
line.unit_discount_amount = Decimal("2.5")
line.unit_discount_type = DiscountValueType.FIXED
@@ -709,6 +730,7 @@ def test_delete_discount_from_order_line(
line.refresh_from_db()
assert line.unit_price == line_undiscounted_price
+ assert line.total_price == line_undiscounted_total_price
unit_discount = line.unit_discount
currency = order.currency
assert unit_discount == Money(Decimal(0), currency=currency)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 8010c140c4..8388f4063d 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -3888,9 +3888,7 @@ def test_order_mark_as_paid_with_external_reference(
assert event_order_paid.user == staff_user
event_reference = event_order_paid.parameters.get("transaction_reference")
assert event_reference == transaction_reference
- order_payments = order.payments.filter(
- transactions__searchable_key=transaction_reference
- )
+ order_payments = order.payments.filter(psp_reference=transaction_reference)
assert order_payments.count() == 1
@@ -5609,10 +5607,10 @@ def test_orders_query_with_filter_search(
]
)
order_with_payment = orders[1]
- payment = Payment.objects.create(order=order_with_payment)
- payment.transactions.create(
- gateway_response={}, is_success=True, searchable_key="ExternalID"
+ payment = Payment.objects.create(
+ order=order_with_payment, psp_reference="ExternalID"
)
+ payment.transactions.create(gateway_response={}, is_success=True)
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 6e372064ff..9e96b3f385 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -305,6 +305,7 @@ def mark_order_as_paid(
email=order.user_email,
total=order.total.gross.amount,
order=order,
+ external_reference=external_reference,
)
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = order.total.gross.amount
@@ -318,7 +319,6 @@ def mark_order_as_paid(
is_success=True,
amount=order.total.gross.amount,
currency=order.total.gross.currency,
- searchable_key=external_reference or "",
gateway_response={},
)
events.order_manually_marked_as_paid_event(
diff --git a/saleor/order/migrations/0109_undiscounted_prices.py b/saleor/order/migrations/0109_undiscounted_prices.py
new file mode 100644
index 0000000000..a698086119
--- /dev/null
+++ b/saleor/order/migrations/0109_undiscounted_prices.py
@@ -0,0 +1,61 @@
+# Generated by Django 3.2.2 on 2021-05-14 12:38
+
+from django.db import migrations, models
+
+
+def set_undiscounted_values(apps, schema_editor):
+ OrderLine = apps.get_model("order", "OrderLine")
+ for line in OrderLine.objects.all().iterator():
+ undiscounted_unit_price_net = (
+ line.unit_price_net_amount + line.unit_discount_amount
+ )
+ undiscounted_unit_price_gross = (
+ line.unit_price_gross_amount + line.unit_discount_amount
+ )
+ line.undiscounted_unit_price_net_amount = undiscounted_unit_price_net
+ line.undiscounted_unit_price_gross_amount = undiscounted_unit_price_gross
+ line.undiscounted_total_price_net_amount = (
+ undiscounted_unit_price_net * line.quantity
+ )
+ line.undiscounted_total_price_gross_amount = (
+ undiscounted_unit_price_gross * line.quantity
+ )
+ line.save(
+ update_fields=[
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_total_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ ]
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0108_origin_not_null"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="orderline",
+ name="undiscounted_total_price_gross_amount",
+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ migrations.AddField(
+ model_name="orderline",
+ name="undiscounted_total_price_net_amount",
+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ migrations.AddField(
+ model_name="orderline",
+ name="undiscounted_unit_price_gross_amount",
+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ migrations.AddField(
+ model_name="orderline",
+ name="undiscounted_unit_price_net_amount",
+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ migrations.RunPython(set_undiscounted_values, migrations.RunPython.noop),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 0c1864dc32..a29b73f7bf 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -15,7 +15,6 @@ from django.utils.timezone import now
from django_measurement.models import MeasurementField
from django_prices.models import MoneyField, TaxedMoneyField
from measurement.measures import Weight
-from prices import TaxedMoney
from ..account.models import Address
from ..channel.models import Channel
@@ -477,6 +476,38 @@ class OrderLine(models.Model):
currency="currency",
)
+ undiscounted_unit_price_gross_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ )
+ undiscounted_unit_price_net_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ )
+ undiscounted_unit_price = TaxedMoneyField(
+ net_amount_field="undiscounted_unit_price_net_amount",
+ gross_amount_field="undiscounted_unit_price_gross_amount",
+ currency="currency",
+ )
+
+ undiscounted_total_price_gross_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ )
+ undiscounted_total_price_net_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ )
+ undiscounted_total_price = TaxedMoneyField(
+ net_amount_field="undiscounted_total_price_net_amount",
+ gross_amount_field="undiscounted_total_price_gross_amount",
+ currency="currency",
+ )
+
tax_rate = models.DecimalField(
max_digits=5, decimal_places=4, default=Decimal("0.0")
)
@@ -493,10 +524,6 @@ class OrderLine(models.Model):
else self.product_name
)
- @property
- def undiscounted_unit_price(self) -> "TaxedMoney":
- return self.unit_price + self.unit_discount
-
@property
def quantity_unfulfilled(self):
return self.quantity - self.quantity_fulfilled
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index a11d087fc1..28a2ae52b9 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -148,11 +148,11 @@ def test_mark_as_paid_with_external_reference(admin_user, draft_order):
payment = draft_order.payments.last()
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.captured_amount == draft_order.total.gross.amount
+ assert payment.psp_reference == external_reference
assert draft_order.events.last().type == (OrderEvents.ORDER_MARKED_AS_PAID)
transactions = payment.transactions.all()
assert transactions.count() == 1
assert transactions[0].kind == TransactionKind.EXTERNAL
- assert transactions[0].searchable_key == external_reference
assert transactions[0].token == external_reference
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 78848402e3..82ceeb9090 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -79,6 +79,36 @@ def test_change_quantity_generates_proper_event(
}
+def test_change_quantity_update_line_fields(
+ order_with_lines,
+ staff_user,
+):
+ # given
+ line = order_with_lines.lines.last()
+ line_info = OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=line.allocations.first().stock.warehouse.pk,
+ )
+ new_quantity = 5
+
+ # when
+ change_order_line_quantity(
+ staff_user,
+ line_info,
+ line.quantity,
+ new_quantity,
+ order_with_lines.channel.slug,
+ )
+
+ # then
+ line.refresh_from_db()
+ assert line.quantity == new_quantity
+ assert line.total_price == line.unit_price * new_quantity
+ assert line.undiscounted_total_price == line.undiscounted_unit_price * new_quantity
+
+
def test_match_orders_with_new_user(customer_user, channel_USD):
address = customer_user.default_billing_address.get_copy()
order = Order.objects.create(
@@ -183,6 +213,10 @@ def test_get_valid_shipping_methods_for_order_shipping_not_required(
def test_update_taxes_for_order_lines(order_with_lines):
# given
+ line_with_discount = order_with_lines.lines.first()
+ line_with_discount.unit_discount_amount = Decimal("2.00")
+ line_with_discount.save(update_fields=["unit_discount_amount"])
+
unit_price = TaxedMoney(net=Money("10.23", "USD"), gross=Money("15.80", "USD"))
total_price = TaxedMoney(net=Money("30.34", "USD"), gross=Money("36.49", "USD"))
tax_rate = Decimal("0.23")
@@ -202,6 +236,15 @@ def test_update_taxes_for_order_lines(order_with_lines):
assert line.unit_price == unit_price
assert line.total_price == total_price
assert line.tax_rate == tax_rate
+ if line.pk != line_with_discount.pk:
+ assert line.undiscounted_unit_price == unit_price
+ assert line.undiscounted_total_price == total_price
+ else:
+ assert line.undiscounted_unit_price == unit_price + line.unit_discount
+ assert (
+ line.undiscounted_total_price
+ == (unit_price + line.unit_discount) * line.quantity
+ )
def test_add_variant_to_order(order, customer_user, variant):
@@ -221,4 +264,6 @@ def test_add_variant_to_order(order, customer_user, variant):
# then
assert line.unit_price == unit_price
assert line.total_price == total_price
+ assert line.undiscounted_unit_price == unit_price
+ assert line.undiscounted_total_price == total_price
assert line.tax_rate == tax_rate
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index d7d6284a78..0d886f4a35 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -197,6 +197,12 @@ def update_taxes_for_order_line(
total_price = manager.calculate_order_line_total(order, line, variant, product)
line.unit_price = unit_price
line.total_price = total_price
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = (
+ line.undiscounted_unit_price * line.quantity
+ if line.unit_discount
+ else total_price
+ )
if unit_price.tax and unit_price.net:
line.tax_rate = manager.get_order_line_tax_rate(
order, product, variant, None, unit_price
@@ -216,6 +222,10 @@ def update_taxes_for_order_lines(
"unit_price_gross_amount",
"total_price_net_amount",
"total_price_gross_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
],
)
@@ -346,6 +356,8 @@ def add_variant_to_order(
total_price = manager.calculate_order_line_total(order, line, variant, product)
line.unit_price = unit_price
line.total_price = total_price
+ line.undiscounted_unit_price = unit_price
+ line.undiscounted_total_price = total_price
line.tax_rate = manager.get_order_line_tax_rate(
order, product, variant, None, unit_price
)
@@ -356,6 +368,10 @@ def add_variant_to_order(
"unit_price_gross_amount",
"total_price_net_amount",
"total_price_gross_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
"tax_rate",
]
)
@@ -433,11 +449,25 @@ def change_order_line_quantity(
line.total_price_gross_amount = total_price_gross_amount.quantize(
Decimal("0.001")
)
+ undiscounted_total_price_gross_amount = (
+ line.quantity * line.undiscounted_unit_price_gross_amount
+ )
+ undiscounted_total_price_net_amount = (
+ line.quantity * line.undiscounted_unit_price_net_amount
+ )
+ line.undiscounted_total_price_gross_amount = (
+ undiscounted_total_price_gross_amount.quantize(Decimal("0.001"))
+ )
+ line.undiscounted_total_price_net_amount = (
+ undiscounted_total_price_net_amount.quantize(Decimal("0.001"))
+ )
line.save(
update_fields=[
"quantity",
"total_price_net_amount",
"total_price_gross_amount",
+ "undiscounted_total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
]
)
else:
@@ -750,6 +780,12 @@ def update_discount_for_order_line(
order_line.unit_discount_type = value_type
order_line.unit_discount_value = value
order_line.total_price = order_line.unit_price * order_line.quantity
+ order_line.undiscounted_unit_price = (
+ order_line.unit_price + order_line.unit_discount
+ )
+ order_line.undiscounted_total_price = (
+ order_line.quantity * order_line.undiscounted_unit_price
+ )
fields_to_update.extend(
[
"tax_rate",
@@ -761,6 +797,10 @@ def update_discount_for_order_line(
"unit_price_net_amount",
"total_price_net_amount",
"total_price_gross_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
]
)
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 4edc9a3632..c68de6c451 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -372,7 +372,7 @@ class AdyenGatewayPlugin(BasePlugin):
kind = TransactionKind.PENDING
elif adyen_auto_capture:
kind = TransactionKind.CAPTURE
- searchable_key = result.message.get("pspReference", "")
+ psp_reference = result.message.get("pspReference", "")
action = result.message.get("action")
error_message = result.message.get("refusalReason")
if action:
@@ -406,7 +406,7 @@ class AdyenGatewayPlugin(BasePlugin):
raw_response=result.message,
action_required_data=action,
payment_method_info=payment_method_info,
- searchable_key=searchable_key,
+ psp_reference=psp_reference,
)
@classmethod
@@ -473,7 +473,7 @@ class AdyenGatewayPlugin(BasePlugin):
transaction_id=result.message.get("pspReference", ""),
error=result.message.get("refusalReason"),
raw_response=result.message,
- searchable_key=result.message.get("pspReference", ""),
+ psp_reference=result.message.get("pspReference", ""),
payment_method_info=payment_method_info,
)
@@ -615,7 +615,7 @@ class AdyenGatewayPlugin(BasePlugin):
transaction_id=result.message.get("pspReference", ""),
error="",
raw_response=result.message,
- searchable_key=result.message.get("pspReference", ""),
+ psp_reference=result.message.get("pspReference", ""),
)
@require_active_plugin
@@ -645,7 +645,7 @@ class AdyenGatewayPlugin(BasePlugin):
error="",
raw_response=result.message,
payment_method_info=payment_method_info,
- searchable_key=result.message.get("pspReference", ""),
+ psp_reference=result.message.get("pspReference", ""),
)
@require_active_plugin
@@ -674,7 +674,7 @@ class AdyenGatewayPlugin(BasePlugin):
transaction_id=result.message.get("pspReference", ""),
error="",
raw_response=result.message,
- searchable_key=result.message.get("pspReference", ""),
+ psp_reference=result.message.get("pspReference", ""),
)
@classmethod
diff --git a/saleor/payment/gateways/adyen/tests/test_plugin.py b/saleor/payment/gateways/adyen/tests/test_plugin.py
index a896ede66a..2279baa89a 100644
--- a/saleor/payment/gateways/adyen/tests/test_plugin.py
+++ b/saleor/payment/gateways/adyen/tests/test_plugin.py
@@ -43,7 +43,7 @@ def test_process_additional_action(
transaction_id="ref-id",
error=None,
raw_response=expected_message,
- searchable_key="ref-id",
+ psp_reference="ref-id",
payment_method_info=PaymentMethodInfo(),
)
mocked_api_call.assert_called_with(
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 6e731cf326..cedef66bd7 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -127,7 +127,7 @@ def create_new_transaction(notification, payment, kind):
currency=currency,
error="",
raw_response={},
- searchable_key=transaction_id,
+ psp_reference=transaction_id,
)
return create_transaction(
payment,
@@ -785,7 +785,7 @@ def handle_api_response(
error=error_message,
raw_response=response.message,
action_required_data=response.message.get("action"),
- searchable_key=response.message.get("pspReference", ""),
+ psp_reference=response.message.get("pspReference", ""),
)
create_transaction(
diff --git a/saleor/payment/gateways/authorize_net/__init__.py b/saleor/payment/gateways/authorize_net/__init__.py
index 0e0be6211a..2df6052e1c 100644
--- a/saleor/payment/gateways/authorize_net/__init__.py
+++ b/saleor/payment/gateways/authorize_net/__init__.py
@@ -177,9 +177,9 @@ def authorize(
transaction_response,
raw_response,
) = _handle_authorize_net_response(response)
- searchable_key = None
+ psp_reference = None
if transaction_id:
- searchable_key = transaction_id
+ psp_reference = transaction_id
elif payment_information.token:
transaction_id = payment_information.token
@@ -203,7 +203,7 @@ def authorize(
kind=kind,
raw_response=raw_response,
customer_id=customer_id,
- searchable_key=str(searchable_key) if searchable_key else None,
+ psp_reference=str(psp_reference) if psp_reference else None,
)
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index d04c38bb66..abd61b2073 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -40,7 +40,7 @@ class GatewayResponse:
# Some gateway can process transaction asynchronously. This value define if we
# should create new transaction based on this response
transaction_already_processed: bool = False
- searchable_key: Optional[str] = None
+ psp_reference: Optional[str] = None
@dataclass
diff --git a/saleor/payment/migrations/0026_payment_psp_reference.py b/saleor/payment/migrations/0026_payment_psp_reference.py
new file mode 100644
index 0000000000..835b55ddc5
--- /dev/null
+++ b/saleor/payment/migrations/0026_payment_psp_reference.py
@@ -0,0 +1,20 @@
+# Generated by Django 3.1.8 on 2021-05-12 09:14
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0025_auto_20210506_0750"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="payment",
+ name="psp_reference",
+ field=models.CharField(
+ blank=True, db_index=True, max_length=512, null=True
+ ),
+ ),
+ ]
diff --git a/saleor/payment/migrations/0027_assign_psp_reference_values.py b/saleor/payment/migrations/0027_assign_psp_reference_values.py
new file mode 100644
index 0000000000..06b90814e5
--- /dev/null
+++ b/saleor/payment/migrations/0027_assign_psp_reference_values.py
@@ -0,0 +1,31 @@
+# Generated by Django 3.2.2 on 2021-05-14 12:08
+
+from django.db import migrations
+
+
+def assign_psp_reference_values(apps, schema_editor):
+ Payment = apps.get_model("payment", "Payment")
+ payments = []
+ for payment in Payment.objects.filter(is_active=True).iterator():
+ txn = (
+ payment.transactions.filter(searchable_key__isnull=False)
+ .exclude(searchable_key="")
+ .first()
+ )
+ if txn:
+ payment.psp_reference = txn.searchable_key
+ payments.append(payment)
+
+ if payments:
+ Payment.objects.bulk_update(payments, ["psp_reference"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0026_payment_psp_reference"),
+ ]
+
+ operations = [
+ migrations.RunPython(assign_psp_reference_values, migrations.RunPython.noop),
+ ]
diff --git a/saleor/payment/migrations/0028_drop_searchable_key.py b/saleor/payment/migrations/0028_drop_searchable_key.py
new file mode 100644
index 0000000000..3c1157bf4b
--- /dev/null
+++ b/saleor/payment/migrations/0028_drop_searchable_key.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.2 on 2021-05-14 12:08
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0027_assign_psp_reference_values"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="transaction",
+ name="searchable_key",
+ ),
+ ]
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index cc5d3cfcaf..4422887a42 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -86,6 +86,9 @@ class Payment(models.Model):
customer_ip_address = models.GenericIPAddressField(blank=True, null=True)
extra_data = models.TextField(blank=True, default="")
return_url = models.URLField(blank=True, null=True)
+ psp_reference = models.CharField(
+ max_length=512, null=True, blank=True, db_index=True
+ )
class Meta:
ordering = ("pk",)
@@ -221,9 +224,6 @@ class Transaction(models.Model):
customer_id = models.CharField(max_length=256, null=True)
gateway_response = JSONField(encoder=DjangoJSONEncoder)
already_processed = models.BooleanField(default=False)
- searchable_key = models.CharField(
- max_length=512, null=True, blank=True, db_index=True
- )
class Meta:
ordering = ("pk",)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index ca0ed6053c..f88acc47b6 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -80,6 +80,7 @@ def create_payment(
checkout: Checkout = None,
order: Order = None,
return_url: str = None,
+ external_reference: Optional[str] = None,
) -> Payment:
"""Create a payment instance.
@@ -127,6 +128,7 @@ def create_payment(
"gateway": gateway,
"total": total,
"return_url": return_url,
+ "psp_reference": external_reference or "",
}
payment, _ = Payment.objects.get_or_create(defaults=defaults, **data)
@@ -183,7 +185,6 @@ def create_transaction(
customer_id=gateway_response.customer_id,
gateway_response=gateway_response.raw_response or {},
action_required_data=gateway_response.action_required_data or {},
- searchable_key=gateway_response.searchable_key or "",
)
return txn
@@ -246,15 +247,23 @@ def validate_gateway_response(response: GatewayResponse):
@transaction.atomic
def gateway_postprocess(transaction, payment):
- if not transaction.is_success:
+ changed_fields = []
+ psp_reference = transaction.gateway_response.get("pspReference")
+ if psp_reference:
+ payment.psp_reference = psp_reference
+ changed_fields.append("psp_reference")
+
+ if not transaction.is_success or transaction.already_processed:
+ if changed_fields:
+ payment.save(update_fields=changed_fields)
return
+
if transaction.action_required:
payment.to_confirm = True
- payment.save(update_fields=["to_confirm"])
- return
- if transaction.already_processed:
+ changed_fields.append("to_confirm")
+ payment.save(update_fields=changed_fields)
return
- changed_fields = []
+
# to_confirm is defined by the transaction.action_required. Payment doesn't
# require confirmation when we got action_required == False
if payment.to_confirm:
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 6e99b70cb3..11e504ea54 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2198,6 +2198,8 @@ def order_line(order, variant):
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
@@ -2234,6 +2236,8 @@ def order_line_with_allocation_in_many_stocks(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
@@ -2279,6 +2283,8 @@ def order_line_with_one_allocation(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
@@ -2359,6 +2365,8 @@ def order_with_lines(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
Allocation.objects.create(
@@ -2404,6 +2412,8 @@ def order_with_lines(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
Allocation.objects.create(
@@ -2524,6 +2534,8 @@ def order_with_lines_channel_PLN(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
Allocation.objects.create(
@@ -2569,6 +2581,8 @@ def order_with_lines_channel_PLN(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
Allocation.objects.create(
@@ -2617,6 +2631,8 @@ def order_with_line_without_inventory_tracking(
variant=variant,
unit_price=unit_price,
total_price=unit_price * quantity,
+ undiscounted_unit_price=unit_price,
+ undiscounted_total_price=unit_price * quantity,
tax_rate=Decimal("0.23"),
)
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 88b8114875..5e9bf7b7d6 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -64,6 +64,8 @@ ORDER_FIELDS = (
"weight",
"private_metadata",
"metadata",
+ "undiscounted_total_net_amount",
+ "undiscounted_total_gross_amount",
)
@@ -97,6 +99,10 @@ def generate_order_lines_payload(lines: Iterable[OrderLine]):
"unit_discount_reason",
"total_price_net_amount",
"total_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_unit_price_gross_amount",
+ "undiscounted_total_price_net_amount",
+ "undiscounted_total_price_gross_amount",
"tax_rate",
)
serializer = PayloadSerializer()
@@ -122,6 +128,7 @@ def generate_order_payload(order: "Order"):
"created",
"modified",
"charge_status",
+ "psp_reference",
"total",
"captured_amount",
"currency",
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 1ad857196d..5d6a4fab83 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -26,6 +26,10 @@ def test_generate_order_payload(
mocked_fulfillment_lines, order_with_lines, fulfilled_order, payment_txn_captured
):
mocked_fulfillment_lines.return_value = "{}"
+
+ payment_txn_captured.psp_reference = "123"
+ payment_txn_captured.save(update_fields=["psp_reference"])
+
new_order = Order.objects.create(
channel=order_with_lines.channel,
billing_address=order_with_lines.billing_address,
@@ -59,7 +63,6 @@ def test_generate_order_payload(
for field in ORDER_FIELDS:
assert payload.get(field) is not None
- assert payload.get("payments")
assert payload.get("shipping_method")
assert payload.get("shipping_tax_rate")
assert payload.get("lines")
@@ -68,6 +71,35 @@ def test_generate_order_payload(
assert payload.get("fulfillments")
assert payload.get("discounts")
assert payload.get("original") == graphene.Node.to_global_id("Order", new_order.pk)
+ assert payload.get("payments")
+ assert len(payload.get("payments")) == 1
+ payments_data = payload.get("payments")[0]
+ assert payments_data == {
+ "id": graphene.Node.to_global_id("Payment", payment_txn_captured.pk),
+ "gateway": payment_txn_captured.gateway,
+ "payment_method_type": payment_txn_captured.payment_method_type,
+ "cc_brand": payment_txn_captured.cc_brand,
+ "is_active": payment_txn_captured.is_active,
+ "created": ANY,
+ "modified": ANY,
+ "charge_status": payment_txn_captured.charge_status,
+ "psp_reference": payment_txn_captured.psp_reference,
+ "total": str(payment_txn_captured.total),
+ "type": "Payment",
+ "captured_amount": str(payment_txn_captured.captured_amount),
+ "currency": payment_txn_captured.currency,
+ "billing_email": payment_txn_captured.billing_email,
+ "billing_first_name": payment_txn_captured.billing_first_name,
+ "billing_last_name": payment_txn_captured.billing_last_name,
+ "billing_company_name": payment_txn_captured.billing_company_name,
+ "billing_address_1": payment_txn_captured.billing_address_1,
+ "billing_address_2": payment_txn_captured.billing_address_2,
+ "billing_city": payment_txn_captured.billing_city,
+ "billing_city_area": payment_txn_captured.billing_city_area,
+ "billing_postal_code": payment_txn_captured.billing_postal_code,
+ "billing_country_code": payment_txn_captured.billing_country_code,
+ "billing_country_area": payment_txn_captured.billing_country_area,
+ }
mocked_fulfillment_lines.assert_called_with(fulfillment)
@@ -108,6 +140,8 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
line = order_line_with_one_allocation
line.unit_discount_amount = Decimal("10.0")
line.unit_discount_type = DiscountValueType.FIXED
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
line.save()
payload = json.loads(generate_order_payload(order))[0]
@@ -120,6 +154,18 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
unit_gross_amount = line.unit_price_gross_amount.quantize(Decimal("0.001"))
unit_discount_amount = line.unit_discount_amount.quantize(Decimal("0.001"))
allocation = line.allocations.first()
+ undiscounted_unit_price_net_amount = (
+ line.undiscounted_unit_price.net.amount.quantize(Decimal("0.001"))
+ )
+ undiscounted_unit_price_gross_amount = (
+ line.undiscounted_unit_price.gross.amount.quantize(Decimal("0.001"))
+ )
+ undiscounted_total_price_net_amount = (
+ line.undiscounted_total_price.net.amount.quantize(Decimal("0.001"))
+ )
+ undiscounted_total_price_gross_amount = (
+ line.undiscounted_total_price.gross.amount.quantize(Decimal("0.001"))
+ )
total_line = line.total_price
global_warehouse_id = graphene.Node.to_global_id(
@@ -151,6 +197,14 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
"quantity_allocated": allocation.quantity_allocated,
}
],
+ "undiscounted_unit_price_net_amount": str(undiscounted_unit_price_net_amount),
+ "undiscounted_unit_price_gross_amount": str(
+ undiscounted_unit_price_gross_amount
+ ),
+ "undiscounted_total_price_net_amount": str(undiscounted_total_price_net_amount),
+ "undiscounted_total_price_gross_amount": str(
+ undiscounted_total_price_gross_amount
+ ),
}
@@ -273,6 +327,12 @@ def test_generate_invoice_payload(fulfilled_order):
"total_net_amount": "80.000",
"total_gross_amount": "98.400",
"weight": "0.0:g",
+ "undiscounted_total_net_amount": str(
+ fulfilled_order.undiscounted_total_net_amount
+ ),
+ "undiscounted_total_gross_amount": str(
+ fulfilled_order.undiscounted_total_gross_amount
+ ),
},
"number": "01/12/2020/TEST",
"created": ANY,