Skip to content

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

Merge branch 'master' into feature/variants_and_shipping_zones_per_channel

IKarbowiak9738bdf8608a
diff --cc saleor/graphql/order/mutations/orders.py
index 2272f3ff13,d1cc672b48..f825076f75
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@@ -547,8 -601,238 +601,242 @@@ class OrderConfirm(ModelMutation)
order.status = OrderStatus.UNFULFILLED
order.save(update_fields=["status"])
payment = order.get_last_payment()
+ manager = info.context.plugins
if payment and payment.is_authorized and payment.can_capture():
- gateway.capture(payment)
- order_captured(order, info.context.user, payment.total, payment)
- order_confirmed(order, info.context.user, send_confirmation_email=True)
+ gateway.capture(payment, info.context.plugins)
+ order_captured(order, info.context.user, payment.total, payment, manager)
+ order_confirmed(order, info.context.user, manager, send_confirmation_email=True)
return OrderConfirm(order=order)
+
+
+ class EditableOrderValidationMixin:
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def validate_order(cls, order):
+ if order.status not in ORDER_EDITABLE_STATUS:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Only draft and unconfirmed orders can be edited.",
+ code=OrderErrorCode.NOT_EDITABLE,
+ )
+ }
+ )
+
+
+ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
+ order = graphene.Field(Order, description="Related order.")
+ order_lines = graphene.List(
+ graphene.NonNull(OrderLine), description="List of added order lines."
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of the order to add the lines to."
+ )
+ input = graphene.List(
+ OrderLineCreateInput,
+ required=True,
+ description="Fields required to add order lines.",
+ )
+
+ class Meta:
+ description = "Create order lines for an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def validate_lines(cls, info, data):
+ lines_to_add = []
+ invalid_ids = []
+ for input_line in data.get("input"):
+ variant_id = input_line["variant_id"]
+ variant = cls.get_node_or_error(
+ info, variant_id, "variant_id", only_type=ProductVariant
+ )
+ quantity = input_line["quantity"]
+ if quantity > 0:
+ lines_to_add.append((quantity, variant))
+ else:
+ invalid_ids.append(variant_id)
+ if invalid_ids:
+ raise ValidationError(
+ {
+ "quantity": ValidationError(
+ "Variants quantity must be greater than 0.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ params={"variants": invalid_ids},
+ ),
+ }
+ )
+ return lines_to_add
+
+ @staticmethod
+ def validate_variants(order, variants):
+ try:
+ channel = order.channel
+ validate_product_is_published_in_channel(variants, channel)
+ validate_variant_channel_listings(variants, channel)
+ except ValidationError as error:
+ raise ValidationError({"input": error})
+
+ @staticmethod
+ def add_lines_to_order(order, lines_to_add, user, manager):
+ try:
+ return [
+ add_variant_to_order(
+ order,
+ variant,
+ quantity,
+ user,
+ manager,
+ allocate_stock=order.is_unconfirmed(),
+ )
+ for quantity, variant in lines_to_add
+ ]
+ except TaxError as tax_error:
+ raise ValidationError(
+ "Unable to calculate taxes - %s" % str(tax_error),
+ code=OrderErrorCode.TAX_ERROR.value,
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ cls.validate_order(order)
+ lines_to_add = cls.validate_lines(info, data)
+ variants = [line[1] for line in lines_to_add]
+ cls.validate_variants(order, variants)
+
+ lines = cls.add_lines_to_order(
+ order, lines_to_add, info.context.user, info.context.plugins
+ )
+
+ # Create the products added event
+ events.order_added_products_event(
+ order=order, user=info.context.user, order_lines=lines_to_add
+ )
+
+ recalculate_order(order)
+ return OrderLinesCreate(order=order, order_lines=lines)
+
+
+ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
+ order = graphene.Field(Order, description="A related order.")
+ order_line = graphene.Field(
+ OrderLine, description="An order line that was deleted."
+ )
+
+ class Arguments:
+ id = graphene.ID(description="ID of the order line to delete.", required=True)
+
+ class Meta:
+ description = "Deletes an order line from an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id):
+ line = cls.get_node_or_error(
+ info,
+ id,
+ only_type=OrderLine,
+ )
+ order = line.order
+ cls.validate_order(line.order)
+
+ db_id = line.id
+ warehouse_pk = (
+ line.allocations.first().stock.warehouse.pk
+ if order.is_unconfirmed()
+ else None
+ )
+ line_info = OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=warehouse_pk,
+ )
+ delete_order_line(line_info)
+ line.id = db_id
+
+ # Create the removal event
+ events.order_removed_products_event(
+ order=order, user=info.context.user, order_lines=[(line.quantity, line)]
+ )
+
+ recalculate_order(order)
+ return OrderLineDelete(order=order, order_line=line)
+
+
+ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
+ order = graphene.Field(Order, description="Related order.")
+
+ class Arguments:
+ id = graphene.ID(description="ID of the order line to update.", required=True)
+ input = OrderLineInput(
+ required=True, description="Fields required to update an order line."
+ )
+
+ class Meta:
+ description = "Updates an order line of an order."
+ model = models.OrderLine
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ instance.old_quantity = instance.quantity
+ cleaned_input = super().clean_input(info, instance, data)
+ cls.validate_order(instance.order)
+
+ quantity = data["quantity"]
+ if quantity <= 0:
+ raise ValidationError(
+ {
+ "quantity": ValidationError(
+ "Ensure this value is greater than 0.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ )
+ }
+ )
+ return cleaned_input
+
+ @classmethod
+ def save(cls, info, instance, cleaned_input):
+ warehouse_pk = (
+ instance.allocations.first().stock.warehouse.pk
+ if instance.order.is_unconfirmed()
+ else None
+ )
+ line_info = OrderLineData(
+ line=instance,
+ quantity=instance.quantity,
+ variant=instance.variant,
+ warehouse_pk=warehouse_pk,
+ )
+ try:
+ change_order_line_quantity(
- info.context.user, line_info, instance.old_quantity, instance.quantity
++ info.context.user,
++ line_info,
++ instance.old_quantity,
++ instance.quantity,
++ instance.order.channel.slug,
+ )
+ except InsufficientStock:
+ raise ValidationError(
+ "Cannot set new quantity because of insufficient stock.",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ )
+ recalculate_order(instance.order)
+
+ @classmethod
+ def success_response(cls, instance):
+ response = super().success_response(instance)
+ response.order = instance.order
+ return response
diff --cc saleor/graphql/order/tests/benchmark/test_order.py
index c45de91150,ce4e436665..1abc24244c
--- a/saleor/graphql/order/tests/benchmark/test_order.py
+++ b/saleor/graphql/order/tests/benchmark/test_order.py
@@@ -8,74 -8,56 +8,74 @@@ from ....checkout.tests.benchmark.test_
from ....tests.utils import get_graphql_content
FRAGMENT_DISCOUNTS = """
- fragment OrderDiscounts on OrderDiscount {
- id
- type
- valueType
- value
- name
- translatedName
- }
+ fragment OrderDiscounts on OrderDiscount {
+ id
+ type
+ valueType
+ value
+ name
+ translatedName
+ }
"""
+FRAGMENT_AVAILABLE_SHIPPING_METHODS = """
+ fragment AvailableShippingMethods on ShippingMethod {
+ id
+ price {
+ amount
+ }
+ minimumOrderPrice {
+ amount
+ currency
+ }
+ type
+ }
+"""
+
FRAGMENT_ORDER_DETAILS = (
FRAGMENT_ADDRESS
+ FRAGMENT_PRODUCT_VARIANT
+ FRAGMENT_DISCOUNTS
+ + FRAGMENT_AVAILABLE_SHIPPING_METHODS
+ """
- fragment OrderDetail on Order {
- userEmail
- paymentStatus
- paymentStatusDisplay
- status
- statusDisplay
- id
- number
- shippingAddress {
- ...Address
- }
- discounts {
- ...OrderDiscounts
- }
- lines {
- productName
- quantity
- variant {
- ...ProductVariant
- }
- unitPrice {
- currency
- ...Price
- }
- }
- availableShippingMethods {
- ...AvailableShippingMethods
- }
- subtotal {
- ...Price
- }
- total {
- ...Price
+ fragment OrderDetail on Order {
+ userEmail
+ paymentStatus
+ paymentStatusDisplay
+ status
+ statusDisplay
+ id
+ number
+ shippingAddress {
+ ...Address
+ }
+ discounts {
+ ...OrderDiscounts
+ }
+ lines {
+ productName
+ quantity
+ variant {
+ ...ProductVariant
}
- shippingPrice {
+ unitPrice {
+ currency
...Price
}
}
++ availableShippingMethods {
++ ...AvailableShippingMethods
++ }
+ subtotal {
+ ...Price
+ }
+ total {
+ ...Price
+ }
+ shippingPrice {
+ ...Price
+ }
+ }
"""
)
diff --cc saleor/graphql/order/tests/test_order.py
index e6f015c3d7,d03aea2c3e..f9bd830c3c
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@@ -2692,40 -2711,55 +2769,79 @@@ def test_order_lines_create
variables = {"orderId": order_id, "variantId": variant_id, "quantity": 0}
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
- data = content["data"]["draftOrderLinesCreate"]
+ data = content["data"]["orderLinesCreate"]
assert data["orderErrors"]
assert data["orderErrors"][0]["field"] == "quantity"
+ assert data["orderErrors"][0]["variants"] == [variant_id]
- def test_draft_order_lines_create_with_unavailable_variant(
++def test_order_lines_create_with_unavailable_variant(
+ draft_order, permission_manage_orders, staff_api_client
+):
- query = DRAFT_ORDER_LINES_CREATE_MUTATION
++ query = ORDER_LINES_CREATE_MUTATION
+ order = draft_order
+ channel = order.channel
+ line = order.lines.first()
+ variant = line.variant
+ variant.channel_listings.filter(channel=channel).update(price_amount=None)
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
- error = content["data"]["draftOrderLinesCreate"]["orderErrors"][0]
++ error = content["data"]["orderLinesCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["field"] == "input"
+ assert error["variants"] == [variant_id]
+
+
- def test_draft_order_lines_create_with_product_and_variant_not_assigned_to_channel(
- draft_order, permission_manage_orders, staff_api_client, variant
+ @pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+ def test_order_lines_create_with_existing_variant(
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+ ):
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ line = order.lines.first()
+ variant = line.variant
+ old_quantity = line.quantity
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+
+ # mutation should fail without proper permissions
+ response = staff_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+ assert not OrderEvent.objects.exists()
+
+ # assign permissions
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query, variables)
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["quantity"] == old_quantity + quantity
+
+
+ @pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+ def test_order_lines_create_with_product_and_variant_not_assigned_to_channel(
+ status, order_with_lines, permission_manage_orders, staff_api_client, variant
):
- query = DRAFT_ORDER_LINES_CREATE_MUTATION
- order = draft_order
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
line = order.lines.first()
assert variant != line.variant
order_id = graphene.Node.to_global_id("Order", order.id)
diff --cc saleor/graphql/product/dataloaders/__init__.py
index 00227afd05,4a82c0e796..c25f50687f
--- a/saleor/graphql/product/dataloaders/__init__.py
+++ b/saleor/graphql/product/dataloaders/__init__.py
@@@ -5,8 -5,8 +5,9 @@@ from .attributes import
VariantAttributesByProductTypeIdLoader,
)
from .products import (
+ AvailableProductVariantsByProductVariantIdAndChannel,
CategoryByIdLoader,
+ CategoryChildrenByCategoryIdLoader,
CollectionByIdLoader,
CollectionChannelListingByCollectionIdAndChannelSlugLoader,
CollectionChannelListingByCollectionIdLoader,
diff --cc saleor/graphql/product/filters.py
index c5d7c7e68d,f9d19f2763..6619cc957d
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@@ -372,12 -368,8 +377,12 @@@ class ProductFilter(MetadataFilterBase)
channel_slug = get_channel_slug_from_filter_data(self.data)
return _filter_is_published(queryset, name, value, channel_slug)
+ def filter_stock_availability(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_stock_availability(queryset, name, value, channel_slug)
+
- class ProductVariantFilter(django_filters.FilterSet):
+ class ProductVariantFilter(MetadataFilterBase):
search = django_filters.CharFilter(
method=filter_fields_containing_value("name", "product__name", "sku")
)
diff --cc saleor/graphql/schema.graphql
index e111965748,3a879d94ec..9f01f5fb8f
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@@ -977,9 -989,14 +995,15 @@@ enum CheckoutErrorCode
ZERO_QUANTITY
MISSING_CHANNEL_SLUG
CHANNEL_INACTIVE
+ UNAVAILABLE_VARIANT_IN_CHANNEL
}
+ type CheckoutLanguageCodeUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ checkout: Checkout
+ checkoutErrors: [CheckoutError!]!
+ }
+
type CheckoutLine implements Node {
id: ID!
variant: ProductVariant!
diff --cc saleor/order/tests/test_order.py
index 3773265b61,4c743e0500..c66fa9e31b
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@@ -581,25 -631,22 +631,24 @@@ def test_order_weight_add_new_variant(o
)
- def test_order_weight_change_line_quantity(order_with_lines):
- line = order_with_lines.lines.first()
- new_quantity = line.quantity + 2
- change_order_line_quantity(None, line, new_quantity, line.quantity)
- order_with_lines.refresh_from_db()
- assert order_with_lines.weight == _calculate_order_weight_from_lines(
- order_with_lines
+ def test_order_weight_change_line_quantity(staff_user, lines_info):
+ line_info = lines_info[0]
+ new_quantity = line_info.quantity + 2
- change_order_line_quantity(staff_user, line_info, new_quantity, line_info.quantity)
+ order = line_info.line.order
++ change_order_line_quantity(
++ staff_user, line_info, new_quantity, line_info.quantity, order.channel.slug
+ )
+ assert order.weight == _calculate_order_weight_from_lines(order)
- def test_order_weight_delete_line(order_with_lines):
- line = order_with_lines.lines.first()
- delete_order_line(line)
- assert order_with_lines.weight == _calculate_order_weight_from_lines(
- order_with_lines
- )
+ def test_order_weight_delete_line(lines_info):
+ order = lines_info[0].line.order
+ line_info = lines_info[0]
+ delete_order_line(line_info)
+ assert order.weight == _calculate_order_weight_from_lines(order)
- def test_get_order_weight_non_existing_product(order_with_lines, product):
+ def test_get_order_weight_non_existing_product(order_with_lines, product, info):
# Removing product should not affect order's weight
order = order_with_lines
variant = product.variants.first()
@@@ -872,26 -919,26 +921,32 @@@ def test_category_voucher_checkout_disc
get_voucher_discount_for_order(order_with_lines)
- def test_ordered_item_change_quantity(transactional_db, order_with_lines):
- assert not order_with_lines.events.count()
- lines = order_with_lines.lines.all()
- change_order_line_quantity(None, lines[1], lines[1].quantity, 0)
- change_order_line_quantity(None, lines[0], lines[0].quantity, 0)
- assert order_with_lines.get_total_quantity() == 0
+ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):
+ order = lines_info[0].line.order
+ assert not order.events.count()
- change_order_line_quantity(staff_user, lines_info[1], lines_info[1].quantity, 0)
- change_order_line_quantity(staff_user, lines_info[0], lines_info[0].quantity, 0)
++ change_order_line_quantity(
++ staff_user, lines_info[1], lines_info[1].quantity, 0, order.channel.slug
++ )
++ change_order_line_quantity(
++ staff_user, lines_info[0], lines_info[0].quantity, 0, order.channel.slug
++ )
+ assert order.get_total_quantity() == 0
def test_change_order_line_quantity_changes_total_prices(
- transactional_db, order_with_lines
+ staff_user, transactional_db, lines_info
):
- assert not order_with_lines.events.count()
- line = order_with_lines.lines.all()[0]
- new_quantity = line.quantity + 1
- change_order_line_quantity(None, line, line.quantity, new_quantity)
- line.refresh_from_db()
- assert line.total_price == line.unit_price * new_quantity
+ order = lines_info[0].line.order
+ assert not order.events.count()
+ line_info = lines_info[0]
+ new_quantity = line_info.quantity + 1
- change_order_line_quantity(staff_user, line_info, line_info.quantity, new_quantity)
++ change_order_line_quantity(
++ staff_user, line_info, line_info.quantity, new_quantity, order.channel.slug
++ )
+ assert line_info.line.total_price == line_info.line.unit_price * new_quantity
- @patch("saleor.order.actions.emails.send_fulfillment_confirmation")
+ @patch("saleor.plugins.manager.PluginsManager.notify")
@pytest.mark.parametrize(
"has_standard,has_digital", ((True, True), (True, False), (False, True))
)
diff --cc saleor/order/tests/test_order_utils.py
index c9d7784c01,4934ed7efa..bd36624144
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@@ -1,13 -1,9 +1,13 @@@
import pytest
- from .. import OrderStatus
+ from .. import OrderLineData, OrderStatus
from ..events import OrderEvents
from ..models import Order, OrderEvent
-from ..utils import change_order_line_quantity, match_orders_with_new_user
+from ..utils import (
+ change_order_line_quantity,
+ get_valid_shipping_methods_for_order,
+ match_orders_with_new_user,
+)
@pytest.mark.parametrize(
@@@ -27,14 -30,23 +34,29 @@@ def test_change_quantity_generates_prop
line = order_with_lines.lines.last()
line.quantity = previous_quantity
+ line_info = OrderLineData(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=line.allocations.first().stock.warehouse.pk,
+ )
+ stock = line.allocations.first().stock
+ stock.quantity = 5
+ stock.save(update_fields=["quantity"])
- change_order_line_quantity(staff_user, line, previous_quantity, new_quantity)
- change_order_line_quantity(staff_user, line_info, previous_quantity, new_quantity)
++ change_order_line_quantity(
++ staff_user,
++ line_info,
++ previous_quantity,
++ new_quantity,
++ order_with_lines.channel.slug,
++ )
if removed_count:
- expected_type = OrderEvents.DRAFT_REMOVED_PRODUCTS
+ expected_type = OrderEvents.REMOVED_PRODUCTS
expected_quantity = removed_count
elif added_count:
- expected_type = OrderEvents.DRAFT_ADDED_PRODUCTS
+ expected_type = OrderEvents.ADDED_PRODUCTS
expected_quantity = added_count
else:
# No event should have occurred
diff --cc saleor/order/utils.py
index 6918ffe558,c5b9850fcf..5a16e97852
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@@ -294,14 -303,18 +303,18 @@@ def add_variant_to_order
Returns an order line the variant was added to.
"""
++ channel = order.channel
try:
line = order.lines.get(variant=variant)
- line.quantity += quantity
- line.save(update_fields=["quantity"])
+ old_quantity = line.quantity
+ new_quantity = old_quantity + quantity
+ line_info = OrderLineData(line=line, quantity=old_quantity)
+ change_order_line_quantity(
- user, line_info, old_quantity, new_quantity, send_event=False
++ user, line_info, old_quantity, new_quantity, channel.slug, send_event=False
+ )
except OrderLine.DoesNotExist:
product = variant.product
collections = product.collections.all()
-- channel = order.channel
channel_listing = variant.channel_listings.get(channel=channel)
unit_price = variant.get_price(
product, collections, channel, channel_listing, discounts
@@@ -343,6 -359,18 +359,19 @@@
]
)
+ if allocate_stock:
+ increase_allocations(
+ [
+ OrderLineData(
+ line=line,
+ quantity=quantity,
+ variant=variant,
+ warehouse_pk=None,
+ )
- ]
++ ],
++ channel.slug,
+ )
+
return line
@@@ -364,9 -392,31 +393,38 @@@ def add_gift_card_to_order(order, gift_
return total_price_left
- def change_order_line_quantity(user, line, old_quantity, new_quantity):
+ def _update_allocations_for_line(
- line_info: OrderLineData, old_quantity: int, new_quantity: int
++ line_info: OrderLineData, old_quantity: int, new_quantity: int, channel_slug: str
+ ):
+ if old_quantity == new_quantity:
+ return
+
+ if not get_order_lines_with_track_inventory([line_info]):
+ return
+
+ if old_quantity < new_quantity:
+ line_info.quantity = new_quantity - old_quantity
- increase_allocations([line_info])
++ increase_allocations([line_info], channel_slug)
+ else:
+ line_info.quantity = old_quantity - new_quantity
+ decrease_allocations([line_info])
+
+
+ def change_order_line_quantity(
- user, line_info, old_quantity: int, new_quantity: int, send_event=True
++ user,
++ line_info,
++ old_quantity: int,
++ new_quantity: int,
++ channel_slug: str,
++ send_event=True,
+ ):
"""Change the quantity of ordered items in a order line."""
+ line = line_info.line
if new_quantity:
+ if line.order.is_unconfirmed():
- _update_allocations_for_line(line_info, old_quantity, new_quantity)
++ _update_allocations_for_line(
++ line_info, old_quantity, new_quantity, channel_slug
++ )
line.quantity = new_quantity
total_price_net_amount = line.quantity * line.unit_price_net_amount
total_price_gross_amount = line.quantity * line.unit_price_gross_amount
diff --cc saleor/plugins/avatax/tests/test_avatax.py
index dca5049a3c,4356e393c6..6a784de63f
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@@ -9,13 -9,7 +9,12 @@@ from django.test import override_settin
from prices import Money, TaxedMoney
from requests import RequestException
- from ....account.models import Address
-from ....checkout.fetch import CheckoutInfo, fetch_checkout_info, fetch_checkout_lines
+from ....checkout.fetch import (
+ CheckoutInfo,
- CheckoutLineInfo,
+ fetch_checkout_info,
+ fetch_checkout_lines,
++ get_valid_shipping_method_list_for_checkout_info,
+)
from ....checkout.utils import add_variant_to_checkout
from ....core.prices import quantize_price
from ....core.taxes import TaxError, TaxType
@@@ -368,6 -323,50 +324,55 @@@ def test_calculate_checkout_subtotal
)
+ @override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+ def test_calculate_checkout_subtotal_for_product_without_tax(
+ checkout,
+ stock,
+ monkeypatch,
+ site_settings,
+ ship_to_pl_address,
+ shipping_zone,
+ address,
+ plugin_configuration,
+ ):
+ plugin_configuration()
+ variant = stock.product_variant
+ product = variant.product
+ product.charge_taxes = False
+ product.save(update_fields=["charge_taxes"])
+
+ monkeypatch.setattr(
+ "saleor.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
+ lambda _: {"PC040156": "desc"},
+ )
+ manager = get_plugins_manager()
+ site_settings.company_address = address
+ site_settings.include_taxes_in_prices = True
+ site_settings.save()
+
+ checkout.shipping_address = ship_to_pl_address
+ checkout.shipping_method = shipping_zone.shipping_methods.get()
+ checkout.save()
+
+ quantity = 2
- add_variant_to_checkout(checkout, variant, quantity)
++ checkout_info = fetch_checkout_info(checkout, [], [], manager)
++ add_variant_to_checkout(checkout_info, variant, quantity)
++
+ lines = fetch_checkout_lines(checkout)
+ assert len(lines) == 1
++ valid_methods = get_valid_shipping_method_list_for_checkout_info(
++ checkout_info, ship_to_pl_address, lines, [], manager
++ )
++ checkout_info.valid_shipping_methods = valid_methods
+
- checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ total = manager.calculate_checkout_subtotal(checkout_info, lines, address, [])
+ total = quantize_price(total, total.currency)
+ expected_total = variant.channel_listings.first().price_amount * quantity
+ assert total == TaxedMoney(
+ net=Money(expected_total, "USD"), gross=Money(expected_total, "USD")
+ )
+
+
@pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_calculate_order_shipping(
@@@ -713,19 -733,88 +739,88 @@@ def test_get_checkout_line_tax_rate_for
)
# then
- assert tax_rate == Decimal("0.055")
+ assert tax_rate == Decimal("0.0")
+ @pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
- def test_get_checkout_line_tax_rate_checkout_not_valid_default_value_returned(
- monkeypatch, checkout_with_item, address, plugin_configuration
+ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
+ monkeypatch,
+ checkout_with_item,
+ address,
+ plugin_configuration,
+ shipping_zone,
+ site_settings,
+ product_with_two_variants,
):
# given
+ site_settings.company_address = address
+ site_settings.save()
plugin_configuration()
monkeypatch.setattr(
- "saleor.plugins.avatax.plugin.get_checkout_tax_data",
- lambda *_: AVALARA_TAX_DATA,
+ "saleor.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",
+ lambda _: {"NT": "Non-Taxable Product"},
)
+ unit_price = TaxedMoney(Money(12, "USD"), Money(12, "USD"))
+
+ manager = get_plugins_manager()
+
+ product_type = ProductType.objects.create(name="non-taxable")
+ product2 = product_with_two_variants
+ product2.product_type = product_type
+ manager.assign_tax_code_to_object_meta(product_type, "NT")
+ product2.save()
+ product_type.save()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+
+ variant2 = product2.variants.first()
- add_variant_to_checkout(checkout_with_item, variant2, 1)
-
- assert checkout_with_item.lines.count() == 2
-
+ checkout_info = CheckoutInfo(
+ checkout=checkout_with_item,
+ shipping_method=checkout_with_item.shipping_method,
+ shipping_address=address,
+ billing_address=None,
+ channel=checkout_with_item.channel,
+ user=None,
+ shipping_method_channel_listings=None,
+ valid_shipping_methods=[],
+ )
++ add_variant_to_checkout(checkout_info, variant2, 1)
++
++ assert checkout_with_item.lines.count() == 2
++
+ lines = fetch_checkout_lines(checkout_with_item)
+ order = [checkout_with_item.lines.first().variant.pk, variant2.pk]
+ lines.sort(key=lambda line: order.index(line.variant.pk))
+
+ # when
+ tax_rates = [
+ manager.get_checkout_line_tax_rate(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ checkout_with_item.shipping_address,
+ [],
+ unit_price,
+ )
+ for checkout_line_info in lines
+ ]
+
+ # then
+ assert tax_rates[0] == Decimal("0.23")
+ assert tax_rates[1] == Decimal("0.0")
+
+
+ @override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+ def test_get_checkout_line_tax_rate_checkout_no_shipping_method_default_value_returned(
+ monkeypatch, checkout_with_item, address, plugin_configuration, site_settings
+ ):
+ # given
+ site_settings.company_address = address
+ site_settings.save()
+ plugin_configuration()
unit_price = TaxedMoney(Money(12, "USD"), Money(15, "USD"))
manager = get_plugins_manager()
diff --cc saleor/product/models.py
index 66af7149b3,3ab610be1f..6534fae89f
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@@ -409,12 -421,13 +423,19 @@@ class ProductVariantQueryset(models.Que
),
)
+ def available_in_channel(self, channel_slug):
+ return self.filter(
+ channel_listings__price_amount__isnull=False,
+ channel_listings__channel__slug=channel_slug,
+ )
+
+ def prefetched_for_webhook(self):
+ return self.prefetch_related(
+ "attributes__values",
+ "attributes__assignment__attribute",
+ "variant_media__media",
+ )
+
class ProductChannelListing(PublishableModel):
product = models.ForeignKey(
diff --cc saleor/warehouse/management.py
index 599f68a1c9,e88f516a50..5793d86890
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@@ -221,7 -219,44 +221,45 @@@ def increase_stock
@transaction.atomic
- def decrease_stock(order_lines_info: Iterable["OrderLineData"]):
-def increase_allocations(lines_info: Iterable["OrderLineData"]):
++def increase_allocations(lines_info: Iterable["OrderLineData"], channel_slug: str):
+ """Increase allocation for order lines with appropriate quantity."""
+ line_pks = [info.line.pk for info in lines_info]
+ allocations = list(
+ Allocation.objects.filter(order_line__in=line_pks)
+ .select_related("stock", "order_line")
+ .select_for_update(of=("self", "stock"))
+ )
+ # evaluate allocations query to trigger select_for_update lock
+ allocation_pks_to_delete = [alloc.pk for alloc in allocations]
+ allocation_quantity_map: Dict[int, list] = defaultdict(list)
+
+ for alloc in allocations:
+ allocation_quantity_map[alloc.order_line.pk].append(alloc.quantity_allocated)
+
+ for line_info in lines_info:
+ allocated = sum(allocation_quantity_map[line_info.line.pk])
+ # line_info.quantity resembles amount to add, sum it with already allocated.
+ line_info.quantity += allocated
+
+ Allocation.objects.filter(pk__in=allocation_pks_to_delete).delete()
+
+ allocate_stocks(
+ lines_info,
+ lines_info[0].line.order.shipping_address.country.code, # type: ignore
++ channel_slug,
+ )
+
+
+ def decrease_allocations(lines_info: Iterable["OrderLineData"]):
+ """Decreate allocations for provided order lines."""
+ tracked_lines = get_order_lines_with_track_inventory(lines_info)
+ if not tracked_lines:
+ return
+ decrease_stock(tracked_lines, update_stocks=False)
+
+
+ @transaction.atomic
+ def decrease_stock(order_lines_info: Iterable["OrderLineData"], update_stocks=True):
"""Decrease stocks quantities for given `order_lines` in given warehouses.
Function deallocate as many quantities as requested if order_line has less quantity
diff --cc saleor/warehouse/tests/test_stock_management.py
index 66a16d159f,e30ccf6086..e983f024e2
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@@ -32,7 -33,7 +33,7 @@@ def test_allocate_stocks(order_line, st
assert allocation.quantity_allocated == 50
- def test_allocate_stocks_multiply_lines(order_line, order, product, stock, channel_USD):
-def test_allocate_stocks_multiple_lines(order_line, order, product, stock):
++def test_allocate_stocks_multiple_lines(order_line, order, product, stock, channel_USD):
stock.quantity = 100
stock.save(update_fields=["quantity"])
@@@ -140,8 -127,8 +141,8 @@@ def test_allocate_stock_insufficient_st
).exists()
- def test_allocate_stock_insufficient_stocks_for_multiply_lines(
+ def test_allocate_stock_insufficient_stocks_for_multiple_lines(
- order_line, variant_with_many_stocks, product
+ order_line, variant_with_many_stocks, product, channel_USD
):
variant = variant_with_many_stocks
stocks = variant.stocks.all()
@@@ -288,6 -275,62 +289,62 @@@ def test_increase_stock_with_new_alloca
assert allocation.quantity_allocated == 50
+ @pytest.mark.parametrize("quantity", (19, 20))
+ def test_increase_allocations(quantity, allocation):
+ order_line = allocation.order_line
+ order_line_info = OrderLineData(
+ line=order_line,
+ quantity=quantity,
+ variant=order_line.variant,
+ warehouse_pk=allocation.stock.warehouse.pk,
+ )
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ initially_allocated = 80
+ allocation.quantity_allocated = initially_allocated
+ allocation.save(update_fields=["quantity_allocated"])
+
- increase_allocations([order_line_info])
++ increase_allocations([order_line_info], order_line.order.channel.slug)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ assert (
+ order_line.allocations.all().aggregate(Sum("quantity_allocated"))[
+ "quantity_allocated__sum"
+ ]
+ == initially_allocated + quantity
+ )
+
+
+ def test_increase_allocation_insufficient_stock(allocation):
+ order_line = allocation.order_line
+ order_line_info = OrderLineData(
+ line=order_line,
+ quantity=21,
+ variant=order_line.variant,
+ warehouse_pk=allocation.stock.warehouse.pk,
+ )
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ initially_allocated = 80
+ allocation.quantity_allocated = initially_allocated
+ allocation.save(update_fields=["quantity_allocated"])
+
+ with pytest.raises(InsufficientStock):
- increase_allocations([order_line_info])
++ increase_allocations([order_line_info], order_line.order.channel.slug)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ assert (
+ order_line.allocations.all().aggregate(Sum("quantity_allocated"))[
+ "quantity_allocated__sum"
+ ]
+ == initially_allocated
+ )
+
+
def test_decrease_stock(allocation):
stock = allocation.stock
stock.quantity = 100