Skip to content

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

Merge branch 'master' into avatax_integration

Maciej Korycinski91bfb4329132
diff --cc saleor/checkout/models.py
index bc34fd58b3,ada30ff0ca..34b9f6e397
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@@ -11,8 -11,9 +11,9 @@@ from django.utils.encoding import smart
from django_prices.models import MoneyField
from ..account.models import Address
- from ..core.taxes import zero_money
-from ..core.utils.taxes import ZERO_MONEY, ZERO_TAXED_MONEY, zero_money
++from ..core.taxes import ZERO_MONEY, zero_money
from ..core.weight import zero_weight
+ from ..giftcard.models import GiftCard
from ..shipping.models import ShippingMethod
CENTS = Decimal("0.01")
@@@ -92,25 -94,34 +94,33 @@@ class Checkout(models.Model)
"""Return `True` if any of the lines requires shipping."""
return any(line.is_shipping_required() for line in self)
- def get_shipping_price(self, taxes):
+ def get_shipping_price(self):
return (
- self.shipping_method.get_total(taxes)
+ self.shipping_method.get_total()
if self.shipping_method and self.is_shipping_required()
- else ZERO_TAXED_MONEY
+ else zero_money()
)
- def get_subtotal(self, discounts=None, taxes=None):
+ def get_subtotal(self, discounts=None):
"""Return the total cost of the checkout prior to shipping."""
- subtotals = (line.get_total(discounts, taxes) for line in self)
- return sum(subtotals, ZERO_TAXED_MONEY)
+ subtotals = (line.get_total(discounts) for line in self)
+ return sum(subtotals, zero_money())
- def get_total(self, discounts=None, taxes=None):
+ def get_total(self, discounts=None):
"""Return the total cost of the checkout."""
- return (
+ total = (
- self.get_subtotal(discounts, taxes)
- + self.get_shipping_price(taxes)
+ self.get_subtotal(discounts)
+ + self.get_shipping_price()
- self.discount_amount
- - self.get_total_gift_cards_balance()
)
- return max(total, ZERO_TAXED_MONEY)
++ return max(total, ZERO_MONEY)
+
+ def get_total_gift_cards_balance(self):
+ """Return the total balance of the gift cards assigned to the checkout."""
+ balance = self.gift_cards.aggregate(models.Sum("current_balance"))[
+ "current_balance__sum"
+ ]
+ return balance or ZERO_MONEY
def get_total_weight(self):
# Cannot use `sum` as it parses an empty Weight to an int
diff --cc saleor/checkout/utils.py
index 8c12d1096e,aa9ac379e2..ba14d4be22
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@@ -15,16 -16,13 +15,21 @@@ from ..account.forms import get_address
from ..account.models import Address, User
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
- from ..core.taxes import ZERO_MONEY
++from ..core.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
+from ..core.taxes.interface import (
+ checkout_are_taxes_handled,
+ get_line_total_gross,
+ get_shipping_gross,
+ get_subtotal_gross,
+ get_total_gross,
+ postprocess_order_creation,
+)
from ..core.utils import to_local_currency
+ from ..core.utils.promo_code import (
+ InvalidPromoCode,
+ promo_code_is_gift_card,
+ promo_code_is_voucher,
+ )
-from ..core.utils.taxes import ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_country
from ..discount import VoucherType
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
@@@ -33,9 -32,14 +39,13 @@@
get_value_voucher_discount,
increase_voucher_usage,
)
+ from ..giftcard.utils import (
+ add_gift_card_code_to_checkout,
+ remove_gift_card_code_from_checkout,
+ )
from ..order import events
from ..order.emails import send_order_confirmation
- from ..order.models import Order
+ from ..order.models import Order, OrderLine
-from ..product.models import ProductVariant
from ..shipping.models import ShippingMethod
from . import AddressType, logger
from .forms import (
@@@ -640,13 -644,13 +650,17 @@@ def change_shipping_address_in_checkout
checkout.save(update_fields=["shipping_address"])
-def get_checkout_context(
- checkout, discounts, taxes, currency=None, shipping_range=None
-):
+def get_checkout_context(checkout, discounts, currency=None, shipping_range=None):
"""Data shared between views in checkout process."""
- checkout_total = get_total_gross(checkout, discounts)
- checkout_total = checkout.get_total(discounts, taxes)
++ checkout_total = (
++ get_total_gross(checkout=checkout, discounts=discounts)
++ - checkout.get_total_gift_cards_balance()
++ )
++ checkout_total = max(checkout_total, ZERO_TAXED_MONEY)
+ checkout_subtotal = get_subtotal_gross(checkout, discounts)
+ shipping_price = get_shipping_gross(checkout, discounts)
+
shipping_required = checkout.is_shipping_required()
- checkout_subtotal = checkout.get_subtotal(discounts, taxes)
total_with_shipping = TaxedMoneyRange(
start=checkout_subtotal, stop=checkout_subtotal
)
@@@ -908,8 -977,101 +976,103 @@@ def _process_user_data_for_order(checko
}
+ def validate_gift_cards(checkout: Checkout):
+ """Check if all gift cards assigned to checkout are available."""
+ if (
+ not checkout.gift_cards.count()
+ == checkout.gift_cards.active(date=date.today()).count()
+ ):
+ msg = pgettext(
+ "Gift card not applicable",
+ "Gift card has expired. Order placement cancelled.",
+ )
+ raise NotApplicable(msg)
+
+
-def create_line_for_order(
- variant: ProductVariant, quantity: int, discounts, taxes
-) -> OrderLine:
++def create_line_for_order(checkout_line: CheckoutLine, discounts) -> OrderLine:
+ """
+ :raises InsufficientStock: when there is not enough items in stock for this variant
+ """
+
++ quantity = checkout_line.quantity
++ variant = checkout_line.variant
+ variant.check_quantity(quantity)
+
+ product_name = variant.display_product()
+ translated_product_name = variant.display_product(translated=True)
+
+ if translated_product_name == product_name:
+ translated_product_name = ""
+
++ total_line_price = get_line_total_gross(checkout_line, discounts)
++ unit_price = total_line_price / checkout_line.quantity
+ line = OrderLine(
+ product_name=product_name,
+ translated_product_name=translated_product_name,
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
+ quantity=quantity,
+ variant=variant,
- unit_price=variant.get_price(discounts, taxes),
- tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes),
++ unit_price=unit_price,
++ tax_rate=unit_price.tax / unit_price.net,
+ )
+
+ return line
+
+
-def prepare_order_data(
- *, checkout: Checkout, tracking_code: str, discounts, taxes
-) -> dict:
++def prepare_order_data(*, checkout: Checkout, tracking_code: str, discounts) -> dict:
+ """
+ Runs checks and returns all the data from a given checkout to create an order.
+
+ :raises NotApplicable InsufficientStock:
+ """
+ order_data = {}
+
- order_data.update(_process_shipping_data_for_order(checkout, taxes))
++ total = (
++ get_total_gross(checkout=checkout, discounts=discounts)
++ - checkout.get_total_gift_cards_balance()
++ )
++ total = max(total, ZERO_TAXED_MONEY)
++
++ shipping_total = get_shipping_gross(checkout, discounts)
++ order_data.update(_process_shipping_data_for_order(checkout, shipping_total))
+ order_data.update(_process_user_data_for_order(checkout))
+ order_data.update(
+ {
+ "language_code": get_language(),
+ "tracking_client_id": tracking_code,
- "total": checkout.get_total(discounts, taxes),
++ "total": total,
+ }
+ )
+
+ order_data["lines"] = [
- create_line_for_order(
- variant=line.variant,
- quantity=line.quantity,
- discounts=discounts,
- taxes=taxes,
- )
++ create_line_for_order(checkout_line=line, discounts=discounts)
+ for line in checkout # type: CheckoutLine
+ ]
+
+ # validate checkout gift cards
+ validate_gift_cards(checkout)
+
+ # Get voucher data (last) as they require a transaction
+ order_data.update(_get_voucher_data_for_order(checkout))
+
+ # assign gift cards to the order
+ order_data["total_price_left"] = (
- checkout.get_subtotal(discounts, taxes)
- + checkout.get_shipping_price(taxes)
++ get_subtotal_gross(checkout, discounts)
++ + shipping_total
+ - checkout.discount_amount
+ ).gross
+
+ return order_data
+
+
+ def abort_order_data(order_data: dict):
+ if "voucher" in order_data:
+ decrease_voucher_usage(order_data["voucher"])
+
+
@transaction.atomic
- def create_order(checkout: Checkout, tracking_code: str, discounts, user: User):
+ def create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
"""Create an order from the checkout.
Each order will get a private copy of both the billing and the shipping
@@@ -951,11 -1109,6 +1110,8 @@@
# assign checkout payments to the order
checkout.payments.update(order=order)
+ postprocess_order_creation(order)
+
- # remove checkout after order is created
- checkout.delete()
-
# Create the order placed
events.order_created_event(order=order, user=user)
@@@ -969,11 -1122,11 +1125,15 @@@ def is_fully_paid(checkout: Checkout, d
Note that these payments may not be captured or charged at all."""
payments = [payment for payment in checkout.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
- checkout_total = get_total_gross(checkout, discounts=discounts).gross
- checkout_total = checkout.get_total(discounts=discounts, taxes=taxes).gross.amount
- return total_paid >= checkout_total
++ checkout_total = (
++ get_total_gross(checkout=checkout, discounts=discounts)
++ - checkout.get_total_gift_cards_balance()
++ )
++ checkout_total = max(checkout_total, ZERO_TAXED_MONEY).gross
+ return total_paid >= checkout_total.amount
-def clean_checkout(checkout: Checkout, taxes, discounts):
+def clean_checkout(checkout: Checkout, discounts):
"""Check if checkout can be completed."""
if checkout.is_shipping_required():
if not checkout.shipping_method:
diff --cc saleor/checkout/views/__init__.py
index 1c6386ca3b,42bfe892fb..0c6faa7509
--- a/saleor/checkout/views/__init__.py
+++ b/saleor/checkout/views/__init__.py
@@@ -4,8 -4,8 +4,12 @@@ from django.shortcuts import get_object
from django.template.response import TemplateResponse
from ...account.forms import LoginForm
- from ...core.taxes import interface as tax_interface
++from ...core.taxes import (
++ ZERO_TAXED_MONEY,
++ get_display_price,
++ interface as tax_interface,
++)
from ...core.utils import format_money, get_user_shipping_country, to_local_currency
-from ...core.utils.taxes import ZERO_TAXED_MONEY, get_display_price
from ...shipping.utils import get_shipping_price_estimate
from ..forms import CheckoutShippingMethodForm, CountryForm, ReplaceCheckoutLineForm
from ..models import Checkout
@@@ -210,20 -216,26 +213,26 @@@ def update_checkout_line(request, check
)
if form.is_valid():
form.save()
+ checkout.refresh_from_db()
+ # Refresh obj from db and confirm that checkout still has this line
+ checkout_line = checkout.lines.filter(variant_id=variant_id).first()
+ line_total = ZERO_TAXED_MONEY
+ if checkout_line:
- line_total = checkout_line.get_total(discounts, taxes)
++ line_total = tax_interface.get_line_total_gross(checkout_line, discounts)
+ subtotal = get_display_price(line_total)
response = {
"variantId": variant_id,
- "subtotal": format_money(
- tax_interface.get_line_total_gross(checkout_line, discounts).gross
- ),
+ "subtotal": format_money(subtotal),
"total": 0,
"checkout": {"numItems": checkout.quantity, "numLines": len(checkout)},
}
- checkout_total = get_display_price(checkout.get_subtotal(discounts, taxes))
+ checkout_total = tax_interface.get_subtotal_gross(checkout, discounts)
- response["total"] = format_money(checkout_total.gross)
++ checkout_total = get_display_price(checkout_total)
+ response["total"] = format_money(checkout_total)
local_checkout_total = to_local_currency(checkout_total, request.currency)
if local_checkout_total is not None:
- response["localTotal"] = format_money(local_checkout_total.gross)
+ response["localTotal"] = format_money(local_checkout_total)
status = 200
elif request.POST is not None:
diff --cc saleor/checkout/views/summary.py
index f51da6e16e,fd20f47be8..520cec8c1f
--- a/saleor/checkout/views/summary.py
+++ b/saleor/checkout/views/summary.py
@@@ -12,6 -12,8 +13,7 @@@ from ..forms import CheckoutNoteFor
from ..utils import (
create_order,
get_checkout_context,
- get_taxes_for_checkout,
+ prepare_order_data,
update_billing_address_in_anonymous_checkout,
update_billing_address_in_checkout,
update_billing_address_in_checkout_with_shipping,
@@@ -30,7 -34,7 +34,6 @@@ def _handle_order_placement(request, ch
checkout=checkout,
tracking_code=analytics.get_client_id(request),
discounts=request.discounts,
- user=request.user,
- taxes=get_taxes_for_checkout(checkout, request.taxes),
)
except InsufficientStock:
return redirect("checkout:index")
@@@ -39,15 -43,13 +42,21 @@@
request, pgettext("Checkout warning", "Please review your checkout.")
)
return redirect("checkout:summary")
+ except TaxError as tax_error:
+ messages.warning(
+ request,
+ pgettext(
+ "Checkout warning", "Unable to calculate taxes - %s" % str(tax_error)
+ ),
+ )
+ return redirect("checkout:summary")
+ # Push the order data into the database
+ order = create_order(checkout=checkout, order_data=order_data, user=request.user)
+
+ # remove checkout after order is created
+ checkout.delete()
+
# Redirect the user to the payment page
return redirect("order:payment", token=order.token)
diff --cc saleor/core/taxes/__init__.py
index 0804b012b8,0000000000..146700aedd
mode 100644,000000..100644
--- a/saleor/core/taxes/__init__.py
+++ b/saleor/core/taxes/__init__.py
@@@ -1,34 -1,0 +1,52 @@@
+from dataclasses import dataclass
++from typing import Union
+
+from django.conf import settings
+from django.contrib.sites.models import Site
- from prices import Money, TaxedMoney
++from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+
+ZERO_MONEY = Money(0, settings.DEFAULT_CURRENCY)
+
+ZERO_TAXED_MONEY = TaxedMoney(net=ZERO_MONEY, gross=ZERO_MONEY)
+
+
+def zero_money():
+ """Function used as a model's default."""
+ return ZERO_MONEY
+
+
+def include_taxes_in_prices():
+ return Site.objects.get_current().settings.include_taxes_in_prices
+
+
+def display_gross_prices():
+ return Site.objects.get_current().settings.display_gross_prices
+
+
+def charge_taxes_on_shipping():
+ return Site.objects.get_current().settings.charge_taxes_on_shipping
+
+
++def get_display_price(
++ base: Union[TaxedMoney, TaxedMoneyRange], display_gross=None
++) -> Money:
++ """Return price amount that should be displayed based on settings"""
++ if not display_gross:
++ display_gross = display_gross_prices()
++ if isinstance(base, TaxedMoneyRange):
++ if display_gross:
++ base = MoneyRange(start=base.start.gross, stop=base.stop.gross)
++ else:
++ base = MoneyRange(start=base.start.net, stop=base.stop.net)
++
++ if isinstance(base, TaxedMoney):
++ base = base.gross if display_gross else base.net
++ return base
++
++
+@dataclass
+class TaxType:
+ """Dataclass for unifying tax type object that comes from tax gateway"""
+
+ code: str
+ description: str
diff --cc saleor/core/templatetags/taxed_prices.py
index afce80c9f6,d816cead25..4742ffa5d6
--- a/saleor/core/templatetags/taxed_prices.py
+++ b/saleor/core/templatetags/taxed_prices.py
@@@ -1,10 -1,7 +1,12 @@@
from django import template
from prices import MoneyRange, TaxedMoney, TaxedMoneyRange
-from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME, get_display_price
++from ...core.taxes import get_display_price
++from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME
++
+# FIXME This const variable belongs to vatlayer, we shouldn't take it directly from
+# vatlayer module. This should be moved to plugin after we will introduce plugin
+# architecture
- from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME
register = template.Library()
diff --cc saleor/core/utils/random_data.py
index 38ef3ff818,ee5cd5983b..f08bfcc3d3
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@@ -24,8 -25,9 +24,9 @@@ from ...core.weight import zero_weigh
from ...dashboard.menu.utils import update_menu
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
+ from ...giftcard.models import GiftCard
from ...menu.models import Menu
-from ...order.models import Fulfillment, Order
+from ...order.models import Fulfillment, Order, OrderLine
from ...order.utils import update_order_status
from ...page.models import Page
from ...payment.utils import (
diff --cc saleor/dashboard/discount/forms.py
index edf6a7cba2,9a879b3ea9..bbea6218bc
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@@ -6,10 -6,10 +6,10 @@@ from django_countries import countrie
from django_prices.forms import MoneyField
from mptt.forms import TreeNodeMultipleChoiceField
+from ...core.taxes import ZERO_MONEY
+ from ...core.utils.promo_code import generate_promo_code
-from ...core.utils.taxes import ZERO_MONEY
from ...discount import DiscountValueType
from ...discount.models import Sale, Voucher
- from ...discount.utils import generate_voucher_code
from ...product.models import Category, Product
from ..forms import AjaxSelect2MultipleChoiceField
diff --cc saleor/graphql/account/types.py
index a21e80a57d,d9082822d7..4e2d23ba93
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@@ -11,7 -11,8 +11,8 @@@ from ...order import models as order_mo
from ..checkout.types import Checkout
from ..core.connection import CountableDjangoObjectType
from ..core.fields import PrefetchingConnectionField
- from ..core.types import CountryDisplay, Image, PermissionDisplay, get_node_optimized
+ from ..core.types import CountryDisplay, Image, PermissionDisplay
-from ..shop.types import get_node_optimized
++from ..core.utils import get_node_optimized
from ..utils import format_permissions_for_display
from .enums import CustomerEventsEnum
diff --cc saleor/graphql/api.py
index 8706f0e254,c5a41f9f32..8cee2e0194
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@@ -2,8 -2,9 +2,9 @@@ import graphen
from .account.schema import AccountMutations, AccountQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
-from .core.schema import CoreMutations
+from .core.schema import CoreMutations, CoreQueries
from .discount.schema import DiscountMutations, DiscountQueries
+ from .giftcard.schema import GiftCardMutations, GiftCardQueries
from .menu.schema import MenuMutations, MenuQueries
from .order.schema import OrderMutations, OrderQueries
from .page.schema import PageMutations, PageQueries
@@@ -17,8 -18,8 +18,9 @@@ from .translations.schema import Transl
class Query(
AccountQueries,
CheckoutQueries,
+ CoreQueries,
DiscountQueries,
+ GiftCardQueries,
MenuQueries,
OrderQueries,
PageQueries,
diff --cc saleor/graphql/checkout/mutations.py
index 12a779e15b,605032cb1f..de5b81803b
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@@ -14,16 -16,19 +16,19 @@@ from ...checkout.utils import
clean_checkout,
create_order,
get_or_create_user_checkout,
- get_taxes_for_checkout,
get_voucher_for_checkout,
+ prepare_order_data,
recalculate_checkout_discount,
+ remove_promo_code_from_checkout,
remove_voucher_from_checkout,
)
from ...core import analytics
from ...core.exceptions import InsufficientStock
-from ...core.utils.taxes import get_taxes_for_address
+from ...core.taxes.errors import TaxError
+from ...core.taxes.interface import get_subtotal_gross
from ...discount import models as voucher_model
from ...payment import PaymentError
+ from ...payment.interface import AddressData
from ...payment.utils import gateway_process_payment
from ...shipping.models import ShippingMethod as ShippingMethodModel
from ..account.i18n import I18nMixin
@@@ -483,26 -503,41 +488,44 @@@ class CheckoutComplete(BaseMutation)
payment = checkout.get_last_active_payment()
- try:
- order = create_order(
- checkout=checkout,
- tracking_code=analytics.get_client_id(info.context),
- discounts=info.context.discounts,
- user=info.context.user,
- )
- except InsufficientStock:
- raise ValidationError("Insufficient product stock.")
- except voucher_model.NotApplicable:
- raise ValidationError("Voucher not applicable")
- except TaxError as tax_error:
- return ValidationError("Unable to calculate taxes - %s" % str(tax_error))
-
- payment.order = order
+ with transaction.atomic():
+ try:
+ order_data = prepare_order_data(
+ checkout=checkout,
+ tracking_code=analytics.get_client_id(info.context),
+ discounts=info.context.discounts,
- taxes=taxes,
+ )
+ except InsufficientStock as e:
+ raise ValidationError(f"Insufficient product stock: {e.item}")
+ except voucher_model.NotApplicable:
+ raise ValidationError("Voucher not applicable")
++ except TaxError as tax_error:
++ return ValidationError(
++ "Unable to calculate taxes - %s" % str(tax_error)
++ )
try:
- gateway_process_payment(payment=payment, payment_token=payment.token)
+ billing_address = order_data["billing_address"] # type: models.Address
+ shipping_address = order_data["shipping_address"] # type: models.Address
+ gateway_process_payment(
+ payment=payment,
+ payment_token=payment.token,
+ billing_address=AddressData(**billing_address.as_data()),
+ shipping_address=AddressData(**shipping_address.as_data()),
+ )
except PaymentError as e:
+ abort_order_data(order_data)
raise ValidationError(str(e))
+
+ # create the order into the database
+ order = create_order(
+ checkout=checkout, order_data=order_data, user=info.context.user
+ )
+
+ # remove checkout after order is successfully paid
+ checkout.delete()
+
+ # return the success response with the newly created order data
return CheckoutComplete(order=order)
diff --cc saleor/graphql/checkout/types.py
index 1e8cd3ae85,8ded1e58ba..02a399ab61
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@@ -3,14 -3,10 +3,16 @@@ import graphene_django_optimizer as gql
from django.conf import settings
from ...checkout import models
-from ...core.utils.taxes import get_taxes_for_address
++from ...core.taxes import ZERO_TAXED_MONEY
+from ...core.taxes.interface import (
+ get_line_total_gross,
+ get_shipping_gross,
+ get_subtotal_gross,
+ get_total_gross,
+)
from ..core.connection import CountableDjangoObjectType
from ..core.types.money import TaxedMoney
+ from ..giftcard.types import GiftCard
from ..order.utils import applicable_shipping_methods
from ..payment.enums import PaymentGatewayEnum
from ..shipping.types import ShippingMethod
@@@ -32,13 -28,14 +34,15 @@@ class CheckoutLine(CountableDjangoObjec
model = models.CheckoutLine
filter_fields = ["id"]
+ @staticmethod
- def resolve_total_price(root: models.CheckoutLine, info):
- taxes = get_taxes_for_address(root.checkout.shipping_address)
- return root.get_total(discounts=info.context.discounts, taxes=taxes)
+ def resolve_total_price(self, info):
+ return get_line_total_gross(
+ checkout_line=self, discounts=info.context.discounts
+ )
- def resolve_requires_shipping(self, *_args):
- return self.is_shipping_required()
+ @staticmethod
+ def resolve_requires_shipping(root: models.CheckoutLine, *_args):
+ return root.is_shipping_required()
class Checkout(CountableDjangoObjectType):
@@@ -104,24 -108,39 +115,39 @@@
interfaces = [graphene.relay.Node]
filter_fields = ["token"]
- def resolve_total_price(self, info):
- return get_total_gross(checkout=self, discounts=info.context.discounts)
+ @staticmethod
+ def resolve_total_price(root: models.Checkout, info):
- taxes = get_taxes_for_address(root.shipping_address)
- return root.get_total(discounts=info.context.discounts, taxes=taxes)
++ taxed_total = (
++ get_total_gross(checkout=root, discounts=info.context.discounts)
++ - root.get_total_gift_cards_balance()
++ )
++ return max(taxed_total, ZERO_TAXED_MONEY)
- def resolve_subtotal_price(self, info):
- return get_subtotal_gross(checkout=self, discounts=info.context.discounts)
+ @staticmethod
+ def resolve_subtotal_price(root: models.Checkout, info):
- taxes = get_taxes_for_address(root.shipping_address)
- return root.get_subtotal(discounts=info.context.discounts, taxes=taxes)
++ return get_subtotal_gross(checkout=root, discounts=info.context.discounts)
- def resolve_shipping_price(self, info):
- return get_shipping_gross(checkout=self, discounts=info.context.discounts)
+ @staticmethod
- def resolve_shipping_price(root: models.Checkout, *_args):
- taxes = get_taxes_for_address(root.shipping_address)
- return root.get_shipping_price(taxes=taxes)
++ def resolve_shipping_price(root: models.Checkout, info):
++ return get_shipping_gross(checkout=root, discounts=info.context.discounts)
- def resolve_lines(self, *_args):
- return self.lines.prefetch_related("variant")
+ @staticmethod
+ def resolve_lines(root: models.Checkout, *_args):
+ return root.lines.prefetch_related("variant")
- def resolve_available_shipping_methods(self, info):
- price = get_subtotal_gross(checkout=self, discounts=info.context.discounts)
- return applicable_shipping_methods(self, price.gross.amount)
+ @staticmethod
+ def resolve_available_shipping_methods(root: models.Checkout, info):
- taxes = get_taxes_for_address(root.shipping_address)
- price = root.get_subtotal(taxes=taxes, discounts=info.context.discounts)
++ price = get_subtotal_gross(checkout=root, discounts=info.context.discounts)
+ return applicable_shipping_methods(root, price.gross.amount)
- def resolve_available_payment_gateways(self, _info):
+ @staticmethod
+ def resolve_available_payment_gateways(_: models.Checkout, _info):
return settings.CHECKOUT_PAYMENT_GATEWAYS.keys()
- def resolve_is_shipping_required(self, _info):
- return self.is_shipping_required()
+ @staticmethod
+ def resolve_gift_cards(root: models.Checkout, _info):
+ return root.gift_cards.all()
+
+ @staticmethod
+ def resolve_is_shipping_required(root: models.Checkout, _info):
+ return root.is_shipping_required()
diff --cc saleor/graphql/payment/mutations.py
index fb705cd4ce,2956a2bc4c..328b34007b
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@@ -2,8 -2,8 +2,9 @@@ import graphen
from django.conf import settings
from django.core.exceptions import ValidationError
++from ...core.taxes import ZERO_TAXED_MONEY
+from ...core.taxes.interface import get_total_gross
from ...core.utils import get_client_ip
-from ...core.utils.taxes import get_taxes_for_address
from ...payment import PaymentError, models
from ...payment.utils import (
create_payment,
@@@ -78,8 -78,12 +79,12 @@@ class CheckoutPaymentCreate(BaseMutatio
raise ValidationError(
{"billing_address": "No billing address associated with this checkout."}
)
- checkout_total = get_total_gross(checkout, discounts=info.context.discounts)
-
- checkout_total = checkout.get_total(
- discounts=info.context.discounts,
- taxes=get_taxes_for_address(checkout.billing_address),
++ checkout_total = (
++ get_total_gross(checkout, discounts=info.context.discounts)
++ - checkout.get_total_gift_cards_balance()
+ )
- amount = data.get("amount", checkout_total)
++ checkout_total = max(checkout_total, ZERO_TAXED_MONEY)
+ amount = data.get("amount", checkout_total.gross.amount)
if amount < checkout_total.gross.amount:
raise ValidationError(
{
diff --cc saleor/graphql/product/types/products.py
index 0b9d5205ae,78069be378..157780d91d
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@@ -265,10 -280,10 +281,10 @@@ class ProductVariant(CountableDjangoObj
@gql_optimizer.resolver_hints(
prefetch_related=("product",), only=["price_override"]
)
- def resolve_pricing(self, info):
+ def resolve_pricing(root: models.ProductVariant, info):
context = info.context
availability = get_variant_availability(
- self, context.discounts, context.country, context.currency
- root, context.discounts, context.taxes, context.currency
++ root, context.discounts, context.country, context.currency
)
return VariantPricingInfo(**availability._asdict())
@@@ -416,12 -436,9 +439,14 @@@ class Product(CountableDjangoObjectType
"weight",
]
- def resolve_tax_type(self, _info):
- tax_data = tax_interface.get_tax_from_object_meta(self)
++ @staticmethod
++ def resolve_tax_type(root: models.Product, _info):
++ tax_data = tax_interface.get_tax_from_object_meta(root)
+ return TaxType(tax_code=tax_data.code, description=tax_data.description)
+
+ @staticmethod
@gql_optimizer.resolver_hints(prefetch_related="images")
- def resolve_thumbnail_url(self, info, *, size=None):
+ def resolve_thumbnail_url(root: models.Product, info, *, size=None):
if not size:
size = 255
url = get_product_image_thumbnail(
@@@ -446,10 -466,10 +474,10 @@@
prefetch_related=("variants", "collections"),
only=["publication_date", "charge_taxes", "price", "tax_rate"],
)
- def resolve_pricing(self, info):
+ def resolve_pricing(root: models.Product, info):
context = info.context
availability = get_product_availability(
- self, context.discounts, context.country, context.currency
- root, context.discounts, context.taxes, context.currency
++ root, context.discounts, context.country, context.currency
)
return ProductPricingInfo(**availability._asdict())
@@@ -466,10 -489,11 +497,14 @@@
prefetch_related=("variants", "collections"),
only=["publication_date", "charge_taxes", "price", "tax_rate"],
)
- def resolve_price(self, info):
- price_range = self.get_price_range(info.context.discounts)
- return price_range.start
+ def resolve_price(root: models.Product, info):
+ price_range = root.get_price_range(info.context.discounts)
- return price_range.start.net
++ price = tax_interface.apply_taxes_to_product(
++ root, price_range.start, info.context.country
++ )
++ return price.net
+ @staticmethod
@gql_optimizer.resolver_hints(
prefetch_related="product_type__product_attributes__values"
)
diff --cc saleor/graphql/shop/types.py
index 535ff404c0,a1f4298773..5a361b01f3
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@@ -10,11 -10,9 +10,10 @@@ from ...core.utils import get_client_ip
from ...menu import models as menu_models
from ...product import models as product_models
from ...site import models as site_models
+from ..account.types import Address
from ..core.enums import WeightUnitsEnum
- from ..core.types import get_node_optimized
from ..core.types.common import CountryDisplay, LanguageDisplay, PermissionDisplay
- from ..core.utils import str_to_enum
+ from ..core.utils import get_node_optimized, str_to_enum
from ..menu.types import Menu
from ..product.types import Collection
from ..translations.enums import LanguageCodeEnum
@@@ -244,14 -259,13 +263,17 @@@ class Shop(graphene.ObjectType)
default_country = None
return default_country
- def resolve_company_address(self, info):
++ @staticmethod
++ def resolve_company_address(_, info):
+ return info.context.site.settings.company_address
+
- def resolve_translation(self, info, language_code):
+ @staticmethod
+ def resolve_translation(_, info, language_code):
return resolve_translation(info.context.site.settings, info, language_code)
+ @staticmethod
@permission_required("site.manage_settings")
- def resolve_automatic_fulfillment_digital_products(self, info):
+ def resolve_automatic_fulfillment_digital_products(_, info):
site_settings = info.context.site.settings
return site_settings.automatic_fulfillment_digital_products
diff --cc saleor/order/models.py
index 3edce3ee9a,3094df0753..caf5e4487e
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@@ -16,10 -16,11 +16,11 @@@ from measurement.measures import Weigh
from prices import Money
from ..account.models import Address
+from ..core.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.utils.json_serializer import CustomJsonEncoder
-from ..core.utils.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.weight import WeightUnits, zero_weight
from ..discount.models import Voucher
+ from ..giftcard.models import GiftCard
from ..payment import ChargeStatus, TransactionKind
from ..shipping.models import ShippingMethod
from . import FulfillmentStatus, OrderEvents, OrderStatus
diff --cc saleor/product/migrations/0094_auto_20190618_0430.py
index 611721ee6f,0000000000..d441533501
mode 100644,000000..100644
--- a/saleor/product/migrations/0094_auto_20190618_0430.py
+++ b/saleor/product/migrations/0094_auto_20190618_0430.py
@@@ -1,34 -1,0 +1,34 @@@
- # Generated by Django 2.2.1 on 2019-06-17 11:24
++# Generated by Django 2.2.1 on 2019-06-18 09:30
+
+import django.contrib.postgres.fields.jsonb
+from django.db import migrations
+
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+
- dependencies = [("product", "0092_auto_20190507_0309")]
++ dependencies = [("product", "0093_auto_20190521_0124")]
+
+ operations = [
+ migrations.AddField(
+ model_name="product",
+ name="meta",
+ field=django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="producttype",
+ name="meta",
+ field=django.contrib.postgres.fields.jsonb.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ ]
diff --cc saleor/product/models.py
index 5588cc9c09,e3037005fa..a4252cc3de
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@@ -19,11 -20,12 +20,11 @@@ from prices import MoneyRang
from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
-from saleor.core.utils import build_absolute_uri
-
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
- from ..core.models import PublishableModel, SortableModel
+ from ..core.models import PublishableModel, PublishedQuerySet, SortableModel
-from ..core.utils.taxes import apply_tax_to_price
+from ..core.utils import build_absolute_uri
+from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
from ..discount.utils import calculate_discounted_price
@@@ -132,8 -140,8 +142,9 @@@ class Product(SeoModel, PublishableMode
weight = MeasurementField(
measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
)
+ meta = JSONField(blank=True, null=True, default=dict, encoder=CustomJsonEncoder)
+ objects = ProductsQueryset.as_manager()
translated = TranslationProxy()
class Meta:
diff --cc tests/api/benchmark/test_checkout.py
index 0000000000,e3394c9376..a9d7936055
mode 000000,100644..100644
--- a/tests/api/benchmark/test_checkout.py
+++ b/tests/api/benchmark/test_checkout.py
@@@ -1,0 -1,521 +1,524 @@@
+ import pytest
+ from django.conf import settings
+ from graphene import Node
++from prices import TaxedMoney
+
+ from saleor.checkout.utils import add_variant_to_checkout
+ from saleor.payment import ChargeStatus, TransactionKind
+ from saleor.payment.models import Payment
+ from tests.api.utils import get_graphql_content
+
+
+ @pytest.fixture()
+ def checkout_with_variant(checkout, variant):
+ add_variant_to_checkout(checkout, variant, 1)
+ checkout.save()
+ return checkout
+
+
+ @pytest.fixture()
+ def checkout_with_shipping_method(checkout_with_variant, shipping_method):
+ checkout = checkout_with_variant
+
+ checkout.shipping_method = shipping_method
+ checkout.save()
+
+ return checkout
+
+
+ @pytest.fixture()
+ def checkout_with_billing_address(checkout_with_shipping_method, address):
+ checkout = checkout_with_shipping_method
+
+ checkout.billing_address = address
+ checkout.save()
+
+ return checkout
+
+
+ @pytest.fixture()
+ def checkout_with_charged_payment(checkout_with_billing_address):
+ checkout = checkout_with_billing_address
+
++ total = checkout.get_total()
++ taxed_total = TaxedMoney(total, total)
+ payment = Payment.objects.create(
+ gateway=settings.DUMMY,
+ is_active=True,
- total=checkout.get_total().gross.amount,
++ total=taxed_total.gross.amount,
+ currency="USD",
+ )
+
+ payment.charge_status = ChargeStatus.FULLY_CHARGED
+ payment.captured_amount = payment.total
+ payment.checkout = checkout_with_billing_address
+ payment.save()
+
+ payment.transactions.create(
+ amount=payment.total,
+ kind=TransactionKind.CAPTURE,
+ gateway_response={},
+ is_success=True,
+ )
+
+ return checkout
+
+
+ @pytest.mark.django_db
+ @pytest.mark.count_queries(autouse=False)
+ def test_create_checkout(api_client, graphql_address_data, variant, count_queries):
+ query = """
+ fragment Price on TaxedMoney {
+ gross {
+ amount
+ localized
+ }
+ currency
+ }
+
+ fragment ProductVariant on ProductVariant {
+ id
+ name
+ price {
+ amount
+ currency
+ localized
+ }
+ product {
+ id
+ name
+ thumbnail {
+ url
+ alt
+ }
+ thumbnail2x: thumbnail(size: 510) {
+ url
+ }
+ }
+ }
+
+ fragment CheckoutLine on CheckoutLine {
+ id
+ quantity
+ totalPrice {
+ ...Price
+ }
+ variant {
+ stockQuantity
+ ...ProductVariant
+ }
+ quantity
+ }
+
+ fragment Address on Address {
+ id
+ firstName
+ lastName
+ companyName
+ streetAddress1
+ streetAddress2
+ city
+ postalCode
+ country {
+ code
+ country
+ }
+ countryArea
+ phone
+ }
+
+ fragment ShippingMethod on ShippingMethod {
+ id
+ name
+ price {
+ currency
+ amount
+ localized
+ }
+ }
+
+ fragment Checkout on Checkout {
+ availablePaymentGateways
+ token
+ id
+ user {
+ email
+ }
+ totalPrice {
+ ...Price
+ }
+ subtotalPrice {
+ ...Price
+ }
+ billingAddress {
+ ...Address
+ }
+ shippingAddress {
+ ...Address
+ }
+ email
+ availableShippingMethods {
+ ...ShippingMethod
+ }
+ shippingMethod {
+ ...ShippingMethod
+ }
+ shippingPrice {
+ ...Price
+ }
+ lines {
+ ...CheckoutLine
+ }
+ }
+
+ mutation createCheckout($checkoutInput: CheckoutCreateInput!) {
+ checkoutCreate(input: $checkoutInput) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ ...Checkout
+ }
+ }
+ }
+ """
+ variables = {
+ "checkoutInput": {
+ "email": "[email protected]",
+ "shippingAddress": graphql_address_data,
+ "lines": [
+ {
+ "quantity": 1,
+ "variantId": Node.to_global_id("ProductVariant", variant.pk),
+ }
+ ],
+ }
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
+ @pytest.mark.django_db
+ @pytest.mark.count_queries(autouse=False)
+ def test_add_shipping_to_checkout(
+ api_client,
+ graphql_address_data,
+ variant,
+ checkout_with_variant,
+ shipping_method,
+ count_queries,
+ ):
+ query = """
+ fragment Price on TaxedMoney {
+ gross {
+ amount
+ localized
+ }
+ currency
+ }
+
+ fragment ProductVariant on ProductVariant {
+ id
+ name
+ price {
+ amount
+ currency
+ localized
+ }
+ product {
+ id
+ name
+ thumbnail {
+ url
+ alt
+ }
+ thumbnail2x: thumbnail(size: 510) {
+ url
+ }
+ }
+ }
+
+ fragment CheckoutLine on CheckoutLine {
+ id
+ quantity
+ totalPrice {
+ ...Price
+ }
+ variant {
+ stockQuantity
+ ...ProductVariant
+ }
+ quantity
+ }
+
+ fragment Address on Address {
+ id
+ firstName
+ lastName
+ companyName
+ streetAddress1
+ streetAddress2
+ city
+ postalCode
+ country {
+ code
+ country
+ }
+ countryArea
+ phone
+ }
+
+ fragment ShippingMethod on ShippingMethod {
+ id
+ name
+ price {
+ currency
+ amount
+ localized
+ }
+ }
+
+ fragment Checkout on Checkout {
+ availablePaymentGateways
+ token
+ id
+ user {
+ email
+ }
+ totalPrice {
+ ...Price
+ }
+ subtotalPrice {
+ ...Price
+ }
+ billingAddress {
+ ...Address
+ }
+ shippingAddress {
+ ...Address
+ }
+ email
+ availableShippingMethods {
+ ...ShippingMethod
+ }
+ shippingMethod {
+ ...ShippingMethod
+ }
+ shippingPrice {
+ ...Price
+ }
+ lines {
+ ...CheckoutLine
+ }
+ }
+
+ mutation updateCheckoutShippingOptions(
+ $checkoutId: ID!
+ $shippingMethodId: ID!
+ ) {
+ checkoutShippingMethodUpdate(
+ checkoutId: $checkoutId
+ shippingMethodId: $shippingMethodId
+ ) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ ...Checkout
+ }
+ }
+ }
+ """
+ variables = {
+ "checkoutId": Node.to_global_id("Checkout", checkout_with_variant.pk),
+ "shippingMethodId": Node.to_global_id("ShippingMethod", shipping_method.pk),
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
+ @pytest.mark.django_db
+ @pytest.mark.count_queries(autouse=False)
+ def test_add_billing_address_to_checkout(
+ api_client, graphql_address_data, checkout_with_shipping_method, count_queries
+ ):
+ query = """
+ fragment Price on TaxedMoney {
+ gross {
+ amount
+ localized
+ }
+ currency
+ }
+
+ fragment ProductVariant on ProductVariant {
+ id
+ name
+ price {
+ amount
+ currency
+ localized
+ }
+ product {
+ id
+ name
+ thumbnail {
+ url
+ alt
+ }
+ thumbnail2x: thumbnail(size: 510) {
+ url
+ }
+ }
+ }
+
+ fragment CheckoutLine on CheckoutLine {
+ id
+ quantity
+ totalPrice {
+ ...Price
+ }
+ variant {
+ stockQuantity
+ ...ProductVariant
+ }
+ quantity
+ }
+
+ fragment Address on Address {
+ id
+ firstName
+ lastName
+ companyName
+ streetAddress1
+ streetAddress2
+ city
+ postalCode
+ country {
+ code
+ country
+ }
+ countryArea
+ phone
+ }
+
+ fragment ShippingMethod on ShippingMethod {
+ id
+ name
+ price {
+ currency
+ amount
+ localized
+ }
+ }
+
+ fragment Checkout on Checkout {
+ availablePaymentGateways
+ token
+ id
+ user {
+ email
+ }
+ totalPrice {
+ ...Price
+ }
+ subtotalPrice {
+ ...Price
+ }
+ billingAddress {
+ ...Address
+ }
+ shippingAddress {
+ ...Address
+ }
+ email
+ availableShippingMethods {
+ ...ShippingMethod
+ }
+ shippingMethod {
+ ...ShippingMethod
+ }
+ shippingPrice {
+ ...Price
+ }
+ lines {
+ ...CheckoutLine
+ }
+ }
+
+ mutation updateCheckoutBillingAddress(
+ $checkoutId: ID!
+ $billingAddress: AddressInput!
+ ) {
+ checkoutBillingAddressUpdate(
+ checkoutId: $checkoutId
+ billingAddress: $billingAddress
+ ) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ ...Checkout
+ }
+ }
+ }
+ """
+ variables = {
+ "checkoutId": Node.to_global_id("Checkout", checkout_with_shipping_method.pk),
+ "billingAddress": graphql_address_data,
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
+ @pytest.mark.django_db
+ @pytest.mark.count_queries(autouse=False)
+ def test_checkout_payment_charge(
+ api_client, graphql_address_data, checkout_with_billing_address, count_queries
+ ):
+ query = """
+ mutation createPayment($input: PaymentInput!, $checkoutId: ID!) {
+ checkoutPaymentCreate(input: $input, checkoutId: $checkoutId) {
+ errors {
+ field
+ message
+ }
+ }
+ }
+ """
+
+ variables = {
+ "checkoutId": Node.to_global_id("Checkout", checkout_with_billing_address.pk),
+ "input": {
+ "billingAddress": graphql_address_data,
+ "amount": 1000, # 10.00 USD * 100
+ "gateway": settings.DUMMY.upper(),
+ "token": "charged",
+ },
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
+ @pytest.mark.django_db
+ @pytest.mark.count_queries(autouse=False)
+ def test_complete_checkout(api_client, checkout_with_charged_payment, count_queries):
+ query = """
+ mutation completeCheckout($checkoutId: ID!) {
+ checkoutComplete(checkoutId: $checkoutId) {
+ errors {
+ field
+ message
+ }
+ order {
+ id
+ token
+ }
+ }
+ }
+ """
+
+ variables = {
+ "checkoutId": Node.to_global_id("Checkout", checkout_with_charged_payment.pk)
+ }
+
+ get_graphql_content(api_client.post_graphql(query, variables))
diff --cc tests/api/test_checkout.py
index ce0c040802,a53c1437b9..a7325ee93a
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@@ -4,12 -4,13 +4,14 @@@ from unittest.mock import ANY, patc
import graphene
import pytest
from django.core.exceptions import ValidationError
+from prices import TaxedMoney
from saleor.checkout.models import Checkout
-from saleor.checkout.utils import clean_checkout, is_fully_paid
-from saleor.core.utils.taxes import ZERO_MONEY
+from saleor.checkout.utils import add_voucher_to_checkout, clean_checkout, is_fully_paid
++from saleor.core.taxes import ZERO_MONEY
from saleor.graphql.core.utils import str_to_enum
from saleor.order.models import Order
+ from saleor.payment import PaymentError
from tests.api.utils import get_graphql_content
MUTATION_CHECKOUT_CREATE = """
@@@ -863,8 -894,7 +895,9 @@@ def test_checkout_complete
checkout_line_quantity = checkout_line.quantity
checkout_line_variant = checkout_line.variant
++ gift_current_balance = checkout.get_total_gift_cards_balance()
total = checkout.get_total()
+ total = TaxedMoney(total, total)
payment = payment_dummy
payment.is_active = True
payment.order = None
@@@ -886,7 -916,7 +919,7 @@@
assert Order.objects.count() == orders_count + 1
order = Order.objects.first()
assert order.token == order_token
-- assert order.total.gross == total.gross
++ assert order.total.gross == total.gross - gift_current_balance
order_line = order.lines.first()
assert checkout_line_quantity == order_line.quantity
@@@ -898,9 -928,68 +931,69 @@@
assert order_payment == payment
assert payment.transactions.count() == 1
- # assert that the checkout instance has been deleted after checkout
- with pytest.raises(Checkout.DoesNotExist):
- checkout.refresh_from_db()
+ gift_card.refresh_from_db()
+ assert gift_card.current_balance == ZERO_MONEY
+ assert gift_card.last_used_on
+
+ assert not Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should have been deleted"
+
+
+ @patch("saleor.graphql.checkout.mutations.gateway_process_payment")
+ def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
+ mocked_process_payment,
+ user_api_client,
+ checkout_with_voucher,
+ voucher,
+ payment_dummy,
+ address,
+ shipping_method,
+ ):
+ def _process_payment(*args, **kwargs):
+ raise PaymentError("Oops! Something went wrong.")
+
+ expected_voucher_usage_count = voucher.used
+ mocked_process_payment.side_effect = _process_payment
+
+ checkout = checkout_with_voucher
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.save()
+
+ total = checkout.get_total()
++ taxed_total = TaxedMoney(total, total)
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
++ payment.total = taxed_total.gross.amount
++ payment.currency = taxed_total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ orders_count = Order.objects.count()
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ variables = {"checkoutId": checkout_id}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["errors"] == [{"field": None, "message": "Oops! Something went wrong."}]
+
+ assert Order.objects.count() == orders_count
+
+ payment.refresh_from_db(fields=["order"])
+ assert payment.transactions.count() == 0
+ assert payment.order is None
+
+ # ensure the voucher usage count was not incremented
+ voucher.refresh_from_db(fields=["used"])
+ assert voucher.used == expected_voucher_usage_count
+
+ assert Checkout.objects.filter(
+ pk=checkout.pk
+ ).exists(), "Checkout should not have been deleted"
def test_checkout_complete_invalid_checkout_id(user_api_client):
@@@ -1294,144 -1380,5 +1387,144 @@@ def test_is_fully_paid_partially_paid(c
def test_is_fully_paid_no_payment(checkout_with_item):
checkout = checkout_with_item
- is_paid = is_fully_paid(checkout, None, None)
+ is_paid = is_fully_paid(checkout, None)
assert not is_paid
+
+
+MUTATION_CHECKOUT_UPDATE_VOUCHER = """
+ mutation($checkoutId: ID!, $voucherCode: String) {
+ checkoutUpdateVoucher(
+ checkoutId: $checkoutId, voucherCode: $voucherCode) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ id,
+ voucherCode
+ }
+ }
+ }
+"""
+
+
+def _mutate_checkout_update_voucher(client, variables):
+ response = client.post_graphql(MUTATION_CHECKOUT_UPDATE_VOUCHER, variables)
+ content = get_graphql_content(response)
+ return content["data"]["checkoutUpdateVoucher"]
+
+
+def test_checkout_add_voucher(api_client, checkout_with_item, voucher):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "voucherCode": voucher.code}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] == voucher.code
+
+
+def test_checkout_remove_voucher(api_client, checkout_with_item):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] is None
+ assert checkout_with_item.voucher_code is None
+
+
+def test_checkout_add_voucher_invalid_checkout(api_client, voucher):
+ variables = {"checkoutId": "XXX", "voucherCode": voucher.code}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "checkoutId"
+
+
+def test_checkout_add_voucher_invalid_code(api_client, checkout_with_item):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "voucherCode": "XXX"}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "voucherCode"
+
+
+def test_checkout_add_voucher_not_applicable_voucher(
+ api_client, checkout_with_item, voucher_with_high_min_amount_spent
+):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "voucherCode": voucher_with_high_min_amount_spent.code,
+ }
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "voucherCode"
+
+
+def test_checkout_lines_delete_with_not_applicable_voucher(
+ user_api_client, checkout_with_item, voucher
+):
+ subtotal = checkout_with_item.get_subtotal()
+ voucher.min_amount_spent = TaxedMoney(subtotal, subtotal).gross
+ voucher.save(update_fields=["min_amount_spent"])
+
- add_voucher_to_checkout(voucher, checkout_with_item)
++ add_voucher_to_checkout(checkout_with_item, voucher)
+ assert checkout_with_item.voucher_code == voucher.code
+
+ line = checkout_with_item.lines.first()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+ variables = {"checkoutId": checkout_id, "lineId": line_id}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLineDelete"]
+ assert not data["errors"]
+ checkout_with_item.refresh_from_db()
+ assert checkout_with_item.lines.count() == 0
+ assert checkout_with_item.voucher_code is None
+
+
+def test_checkout_shipping_address_update_with_not_applicable_voucher(
+ user_api_client,
+ checkout_with_item,
+ voucher_shipping_type,
+ graphql_address_data,
+ address_other_country,
+ shipping_method,
+):
+ assert checkout_with_item.shipping_address is None
+ assert checkout_with_item.voucher_code is None
+
+ checkout_with_item.shipping_address = address_other_country
+ checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+ assert checkout_with_item.shipping_address.country == address_other_country.country
+
+ voucher = voucher_shipping_type
+ assert voucher.countries[0].code == address_other_country.country
+
- add_voucher_to_checkout(voucher, checkout_with_item)
++ add_voucher_to_checkout(checkout_with_item, voucher)
+ assert checkout_with_item.voucher_code == voucher.code
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ new_address = graphql_address_data
+ variables = {"checkoutId": checkout_id, "shippingAddress": new_address}
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+
+ checkout_with_item.refresh_from_db()
+ checkout_with_item.shipping_address.refresh_from_db()
+
+ assert checkout_with_item.shipping_address.country == new_address["country"]
+ assert checkout_with_item.voucher_code is None
diff --cc tests/api/test_checkout_promo_codes.py
index 0000000000,0c72d1f9af..b67e779a68
mode 000000,100644..100644
--- a/tests/api/test_checkout_promo_codes.py
+++ b/tests/api/test_checkout_promo_codes.py
@@@ -1,0 -1,550 +1,553 @@@
+ from datetime import date, timedelta
+
+ import graphene
++from prices import TaxedMoney
++
++from saleor.checkout.utils import add_voucher_to_checkout
+ from tests.api.test_checkout import (
+ MUTATION_CHECKOUT_LINES_DELETE,
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE,
+ )
+ from tests.api.utils import get_graphql_content
+
-from saleor.checkout.utils import add_voucher_to_checkout
-
+ MUTATION_CHECKOUT_UPDATE_VOUCHER = """
+ mutation($checkoutId: ID!, $voucherCode: String) {
+ checkoutUpdateVoucher(
+ checkoutId: $checkoutId, voucherCode: $voucherCode) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ id,
+ voucherCode
+ }
+ }
+ }
+ """
+
+
+ def _mutate_checkout_update_voucher(client, variables):
+ response = client.post_graphql(MUTATION_CHECKOUT_UPDATE_VOUCHER, variables)
+ content = get_graphql_content(response)
+ return content["data"]["checkoutUpdateVoucher"]
+
+
+ def test_checkout_add_voucher(api_client, checkout_with_item, voucher):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "voucherCode": voucher.code}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] == voucher.code
+
+
+ def test_checkout_remove_voucher(api_client, checkout_with_item):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] is None
+ assert checkout_with_item.voucher_code is None
+
+
+ def test_checkout_add_voucher_invalid_checkout(api_client, voucher):
+ variables = {"checkoutId": "XXX", "voucherCode": voucher.code}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "checkoutId"
+
+
+ def test_checkout_add_voucher_invalid_code(api_client, checkout_with_item):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "voucherCode": "XXX"}
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "voucherCode"
+
+
+ def test_checkout_add_voucher_not_applicable_voucher(
+ api_client, checkout_with_item, voucher_with_high_min_amount_spent
+ ):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "voucherCode": voucher_with_high_min_amount_spent.code,
+ }
+ data = _mutate_checkout_update_voucher(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "voucherCode"
+
+
+ def test_checkout_lines_delete_with_not_applicable_voucher(
+ user_api_client, checkout_with_item, voucher
+ ):
- voucher.min_amount_spent = checkout_with_item.get_subtotal().gross
++ subtotal = checkout_with_item.get_subtotal()
++ voucher.min_amount_spent = TaxedMoney(subtotal, subtotal).gross
+ voucher.save(update_fields=["min_amount_spent"])
+
+ add_voucher_to_checkout(checkout_with_item, voucher)
+ assert checkout_with_item.voucher_code == voucher.code
+
+ line = checkout_with_item.lines.first()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+ variables = {"checkoutId": checkout_id, "lineId": line_id}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLineDelete"]
+ assert not data["errors"]
+ checkout_with_item.refresh_from_db()
+ assert checkout_with_item.lines.count() == 0
+ assert checkout_with_item.voucher_code is None
+
+
+ def test_checkout_shipping_address_update_with_not_applicable_voucher(
+ user_api_client,
+ checkout_with_item,
+ voucher_shipping_type,
+ graphql_address_data,
+ address_other_country,
+ shipping_method,
+ ):
+ assert checkout_with_item.shipping_address is None
+ assert checkout_with_item.voucher_code is None
+
+ checkout_with_item.shipping_address = address_other_country
+ checkout_with_item.shipping_method = shipping_method
+ checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
+ assert checkout_with_item.shipping_address.country == address_other_country.country
+
+ voucher = voucher_shipping_type
+ assert voucher.countries[0].code == address_other_country.country
+
+ add_voucher_to_checkout(checkout_with_item, voucher)
+ assert checkout_with_item.voucher_code == voucher.code
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ new_address = graphql_address_data
+ variables = {"checkoutId": checkout_id, "shippingAddress": new_address}
+ response = user_api_client.post_graphql(
+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutShippingAddressUpdate"]
+ assert not data["errors"]
+
+ checkout_with_item.refresh_from_db()
+ checkout_with_item.shipping_address.refresh_from_db()
+
+ assert checkout_with_item.shipping_address.country == new_address["country"]
+ assert checkout_with_item.voucher_code is None
+
+
+ def test_checkout_totals_use_discounts(api_client, checkout_with_item, sale):
+ checkout = checkout_with_item
+ # make sure that we're testing a variant that is actually on sale
+ product = checkout.lines.first().variant.product
+ sale.products.add(product)
+
+ query = """
+ query getCheckout($token: UUID) {
+ checkout(token: $token) {
+ lines {
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ """
+
+ variables = {"token": str(checkout.token)}
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]
+
+ discounts = [sale]
- assert (
- data["totalPrice"]["gross"]["amount"]
- == checkout.get_total(discounts=discounts).gross.amount
- )
- assert (
- data["subtotalPrice"]["gross"]["amount"]
- == checkout.get_subtotal(discounts=discounts).gross.amount
- )
++ total = checkout.get_total(discounts=discounts)
++ taxed_total = TaxedMoney(total, total)
++ assert data["totalPrice"]["gross"]["amount"] == taxed_total.gross.amount
++ assert data["subtotalPrice"]["gross"]["amount"] == taxed_total.gross.amount
+
+ line = checkout.lines.first()
++ line_total = line.get_total(discounts=discounts)
+ assert (
+ data["lines"][0]["totalPrice"]["gross"]["amount"]
- == line.get_total(discounts=discounts).gross.amount
++ == TaxedMoney(line_total, line_total).gross.amount
+ )
+
+
+ QUERY_GET_CHECKOUT_GIFT_CARD_CODES = """
+ query getCheckout($token: UUID!) {
+ checkout(token: $token) {
+ token
+ giftCards {
+ displayCode
+ currentBalance {
+ amount
+ }
+ }
+ }
+ }
+ """
+
+
+ def test_checkout_get_gift_card_code(user_api_client, checkout_with_gift_card):
+ gift_card = checkout_with_gift_card.gift_cards.first()
+ variables = {"token": str(checkout_with_gift_card.token)}
+ response = user_api_client.post_graphql(
+ QUERY_GET_CHECKOUT_GIFT_CARD_CODES, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]["giftCards"][0]
+ assert data["displayCode"] == gift_card.display_code
+ assert data["currentBalance"]["amount"] == gift_card.current_balance.amount
+
+
+ def test_checkout_get_gift_card_codes(
+ user_api_client, checkout_with_gift_card, gift_card_created_by_staff
+ ):
+ checkout_with_gift_card.gift_cards.add(gift_card_created_by_staff)
+ checkout_with_gift_card.save()
+ gift_card_first = checkout_with_gift_card.gift_cards.first()
+ gift_card_last = checkout_with_gift_card.gift_cards.last()
+ variables = {"token": str(checkout_with_gift_card.token)}
+ response = user_api_client.post_graphql(
+ QUERY_GET_CHECKOUT_GIFT_CARD_CODES, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]["giftCards"]
+ assert data[0]["displayCode"] == gift_card_first.display_code
+ assert data[0]["currentBalance"]["amount"] == gift_card_first.current_balance.amount
+ assert data[1]["displayCode"] == gift_card_last.display_code
+ assert data[1]["currentBalance"]["amount"] == gift_card_last.current_balance.amount
+
+
+ def test_checkout_get_gift_card_code_without_gift_card(user_api_client, checkout):
+ variables = {"token": str(checkout.token)}
+ response = user_api_client.post_graphql(
+ QUERY_GET_CHECKOUT_GIFT_CARD_CODES, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkout"]["giftCards"]
+ assert not data
+
+
+ MUTATION_CHECKOUT_ADD_PROMO_CODE = """
+ mutation($checkoutId: ID!, $promoCode: String!) {
+ checkoutAddPromoCode(
+ checkoutId: $checkoutId, promoCode: $promoCode) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ id,
+ voucherCode
+ giftCards {
+ id
+ displayCode
+ }
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ }
+ }
+ }
+ """
+
+
+ def _mutate_checkout_add_promo_code(client, variables):
+ response = client.post_graphql(MUTATION_CHECKOUT_ADD_PROMO_CODE, variables)
+ content = get_graphql_content(response)
+ return content["data"]["checkoutAddPromoCode"]
+
+
+ def test_checkout_add_voucher_code(api_client, checkout_with_item, voucher):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": voucher.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] == voucher.code
+
+
+ def test_checkout_add_voucher_code_not_applicable_voucher(
+ api_client, checkout_with_item, voucher_with_high_min_amount_spent
+ ):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": voucher_with_high_min_amount_spent.code,
+ }
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "promoCode"
+
+
+ def test_checkout_add_gift_card_code(api_client, checkout_with_item, gift_card):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id
+ assert data["checkout"]["giftCards"][0]["displayCode"] == gift_card.display_code
+
+
+ def test_checkout_add_many_gift_card_code(
+ api_client, checkout_with_gift_card, gift_card_created_by_staff
+ ):
+ assert checkout_with_gift_card.gift_cards.count() > 0
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_gift_card.pk)
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card_created_by_staff.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": gift_card_created_by_staff.code,
+ }
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ gift_card_data = data["checkout"]["giftCards"][-1]
+ assert gift_card_data["id"] == gift_card_id
+ assert gift_card_data["displayCode"] == gift_card_created_by_staff.display_code
+
+
+ def test_checkout_get_total_with_gift_card(api_client, checkout_with_item, gift_card):
- total_with_gift_card = (
- checkout_with_item.get_total().gross.amount - gift_card.current_balance
- )
++ total = checkout_with_item.get_total()
++ taxed_total = TaxedMoney(total, total)
++ total_with_gift_card = taxed_total.gross.amount - gift_card.current_balance
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert not data["checkout"]["giftCards"] == []
+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == total_with_gift_card
+
+
+ def test_checkout_get_total_with_many_gift_card(
+ api_client, checkout_with_gift_card, gift_card_created_by_staff
+ ):
++ total = (
++ checkout_with_gift_card.get_total()
++ - checkout_with_gift_card.get_total_gift_cards_balance()
++ )
++ taxed_total = TaxedMoney(total, total)
+ total_with_gift_card = (
- checkout_with_gift_card.get_total().gross.amount
- - gift_card_created_by_staff.current_balance
++ taxed_total.gross.amount - gift_card_created_by_staff.current_balance
+ )
+
+ assert checkout_with_gift_card.gift_cards.count() > 0
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_gift_card.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": gift_card_created_by_staff.code,
+ }
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == total_with_gift_card
+
+
+ def test_checkout_get_total_with_more_money_on_gift_card(
+ api_client, checkout_with_item, gift_card_used
+ ):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card_used.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert not data["checkout"]["giftCards"] == []
+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == 0
+
+
+ def test_checkout_add_same_gift_card_code(api_client, checkout_with_gift_card):
+ gift_card = checkout_with_gift_card.gift_cards.first()
+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)
+ gift_card_count = checkout_with_gift_card.gift_cards.count()
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_gift_card.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["giftCards"][0]["id"] == gift_card_id
+ assert data["checkout"]["giftCards"][0]["displayCode"] == gift_card.display_code
+ assert len(data["checkout"]["giftCards"]) == gift_card_count
+
+
+ def test_checkout_add_gift_card_code_in_active_gift_card(
+ api_client, checkout_with_item, gift_card
+ ):
+ gift_card.is_active = False
+ gift_card.save()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "promoCode"
+
+
+ def test_checkout_add_gift_card_code_in_expired_gift_card(
+ api_client, checkout_with_item, gift_card
+ ):
+ gift_card.end_date = date.today() - timedelta(days=1)
+ gift_card.save()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "promoCode"
+
+
+ def test_checkout_add_promo_code_invalid_checkout(api_client, voucher):
+ variables = {"checkoutId": "unexisting_checkout", "promoCode": voucher.code}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "checkoutId"
+
+
+ def test_checkout_add_promo_code_invalid_promo_code(api_client, checkout_with_item):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": "unexisting_code"}
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "promoCode"
+
+
+ MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """
+ mutation($checkoutId: ID!, $promoCode: String!) {
+ checkoutRemovePromoCode(
+ checkoutId: $checkoutId, promoCode: $promoCode) {
+ errors {
+ field
+ message
+ }
+ checkout {
+ id,
+ voucherCode
+ giftCards {
+ id
+ displayCode
+ }
+ }
+ }
+ }
+ """
+
+
+ def _mutate_checkout_remove_promo_code(client, variables):
+ response = client.post_graphql(MUTATION_CHECKOUT_REMOVE_PROMO_CODE, variables)
+ content = get_graphql_content(response)
+ return content["data"]["checkoutRemovePromoCode"]
+
+
+ def test_checkout_remove_voucher_code(api_client, checkout_with_voucher):
+ assert checkout_with_voucher.voucher_code is not None
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_voucher.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": checkout_with_voucher.voucher_code,
+ }
+
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ checkout_with_voucher.refresh_from_db()
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] is None
+ assert checkout_with_voucher.voucher_code is None
+
+
+ def test_checkout_remove_gift_card_code(api_client, checkout_with_gift_card):
+ assert checkout_with_gift_card.gift_cards.count() == 1
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_gift_card.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": checkout_with_gift_card.gift_cards.first().code,
+ }
+
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["giftCards"] == []
+ assert not checkout_with_gift_card.gift_cards.all().exists()
+
+
+ def test_checkout_remove_one_of_gift_cards(
+ api_client, checkout_with_gift_card, gift_card_created_by_staff
+ ):
+ checkout_with_gift_card.gift_cards.add(gift_card_created_by_staff)
+ checkout_with_gift_card.save()
+ gift_card_first = checkout_with_gift_card.gift_cards.first()
+ gift_card_last = checkout_with_gift_card.gift_cards.last()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_gift_card.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": gift_card_first.code}
+
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ checkout_gift_cards = checkout_with_gift_card.gift_cards
+ assert data["checkout"]["id"] == checkout_id
+ assert checkout_gift_cards.filter(code=gift_card_last.code).exists()
+ assert not checkout_gift_cards.filter(code=gift_card_first.code).exists()
+
+
+ def test_checkout_remove_promo_code_invalid_promo_code(api_client, checkout_with_item):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {"checkoutId": checkout_id, "promoCode": "unexisting_code"}
+
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+
+
+ def test_checkout_remove_promo_code_invalid_checkout(api_client, voucher):
+ variables = {"checkoutId": "unexisting_checkout", "promoCode": voucher.code}
+
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "checkoutId"
diff --cc tests/conftest.py
index 21a800ca26,9285b40cdd..907aa0baaa
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@@ -620,8 -636,33 +647,32 @@@ def order_line(order, variant, vatlayer
)
+ @pytest.fixture
+ def gift_card(customer_user, staff_user):
+ return GiftCard.objects.create(
+ code="mirumee_giftcard",
+ user=customer_user,
+ initial_balance=10,
+ current_balance=10,
+ )
+
+
+ @pytest.fixture
+ def gift_card_used(staff_user):
+ return GiftCard.objects.create(
+ code="gift_card_used", initial_balance=150, current_balance=100
+ )
+
+
+ @pytest.fixture
+ def gift_card_created_by_staff(staff_user):
+ return GiftCard.objects.create(
+ code="mirumee_staff", initial_balance=5, current_balance=5
+ )
+
+
@pytest.fixture()
-def order_with_lines(order, product_type, category, shipping_zone, vatlayer):
- taxes = vatlayer
+def order_with_lines(order, product_type, category, shipping_zone):
product = Product.objects.create(
name="Test product",
price=Money("10.00", "USD"),
diff --cc tests/test_cart.py
index 4242bfc3f1,7f6e6a4cdb..786998965e
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@@ -612,20 -646,41 +597,42 @@@ def test_update_view_must_be_ajax(custo
assert result.status_code == 302
+ def test_update_checkout_line_qunatity_zero(
+ request_checkout_with_item, client, product
+ ):
+ variant = product.variants.filter().first()
+ data = {"quantity": 0}
+ # response = client.post(API_PATH, data, content_type="application/json")
+ response = client.post(
+ reverse("checkout:update-line", kwargs={"variant_id": variant.id}),
+ data=data,
+ HTTP_X_REQUESTED_WITH="XMLHttpRequest",
+ )
+ assert response.status_code == 200
+ expected_response = {
+ "variantId": str(variant.id),
+ "subtotal": "$0.00",
+ "total": "$0.00",
+ "checkout": {"numItems": 0, "numLines": 0},
+ }
+ data = response.json()
+ assert data == expected_response
+
+
-def test_get_checkout_context(request_checkout_with_item, shipping_zone, vatlayer):
- checkout = request_checkout_with_item
+def test_get_checkout_context(checkout_with_single_item, shipping_zone):
shipment_option = get_shipping_price_estimate(
- checkout.get_subtotal().gross, checkout.get_total_weight(), "PL", vatlayer
+ checkout_with_single_item.get_subtotal(),
+ checkout_with_single_item.get_total_weight(),
+ "PL",
)
checkout_data = utils.get_checkout_context(
- checkout, None, vatlayer, currency="USD", shipping_range=shipment_option
+ checkout_with_single_item, None, currency="USD", shipping_range=shipment_option
)
assert checkout_data["checkout_total"] == TaxedMoney(
- net=Money("8.13", "USD"), gross=Money(10, "USD")
+ net=Money("10.00", "USD"), gross=Money("10.00", "USD")
)
assert checkout_data["total_with_shipping"].start == TaxedMoney(
- net=Money("16.26", "USD"), gross=Money(20, "USD")
+ net=Money("20.00", "USD"), gross=Money("20.00", "USD")
)
diff --cc tests/test_checkout.py
index c8ee681862,0cb24e2e85..9a3436beb2
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@@ -575,9 -620,10 +620,10 @@@ def test_create_order_creates_expected_
# Place checkout
order = create_order(
- checkout,
- "tracking_code",
- discounts=None,
+ checkout=checkout,
+ order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
++ checkout=checkout, tracking_code="tracking_code", discounts=None
+ ),
user=customer_user if not is_anonymous_user else AnonymousUser(),
)
@@@ -626,8 -672,11 +672,8 @@@ def test_create_order_insufficient_stoc
request_checkout.save()
with pytest.raises(InsufficientStock):
- create_order(
- request_checkout, "tracking_code", discounts=None, user=customer_user
+ prepare_order_data(
- checkout=request_checkout,
- tracking_code="tracking_code",
- discounts=None,
- taxes=None,
++ checkout=request_checkout, tracking_code="tracking_code", discounts=None
)
@@@ -641,18 -690,121 +687,123 @@@ def test_create_order_doesnt_duplicate_
checkout.shipping_method = shipping_method
checkout.save()
- with patch.object(checkout, "delete") as mocked_delete:
- order_1 = create_order(
- checkout, tracking_code="", discounts=None, user=customer_user
- )
- assert order_1.checkout_token == checkout.token
- order_data = prepare_order_data(
- checkout=checkout, tracking_code="", discounts=None, taxes=None
- )
++ order_data = prepare_order_data(checkout=checkout, tracking_code="", discounts=None)
+
+ order_1 = create_order(checkout=checkout, order_data=order_data, user=customer_user)
+ assert order_1.checkout_token == checkout.token
+
+ order_2 = create_order(checkout=checkout, order_data=order_data, user=customer_user)
+ assert order_1.pk == order_2.pk
- order_2 = create_order(
- checkout, tracking_code="", discounts=None, user=customer_user
- )
- assert order_1.pk == order_2.pk
- assert mocked_delete.call_count == 1
+ @pytest.mark.parametrize("is_anonymous_user", (True, False))
+ def test_create_order_with_gift_card(
+ checkout_with_gift_card, customer_user, shipping_method, is_anonymous_user
+ ):
+ checkout_user = None if is_anonymous_user else customer_user
+ checkout = checkout_with_gift_card
+ checkout.user = checkout_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.shipping_method = shipping_method
+ checkout.save()
+
++ subtotal = checkout.get_subtotal()
++ shipping_price = checkout.get_shipping_price()
+ total_gross_without_gift_cards = (
- checkout.get_subtotal()
- + checkout.get_shipping_price(None)
++ TaxedMoney(subtotal, subtotal)
++ + TaxedMoney(shipping_price, shipping_price)
+ - checkout.discount_amount
+ ).gross
+ gift_cards_balance = checkout.get_total_gift_cards_balance()
+
+ order = create_order(
+ checkout=checkout,
+ order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
++ checkout=checkout, tracking_code="tracking_code", discounts=None
+ ),
+ user=customer_user if not is_anonymous_user else AnonymousUser(),
+ )
+
- assert order.gift_cards.count() > 0
++ assert order.gift_cards.count() == 1
+ assert order.gift_cards.first().current_balance.amount == 0
+ assert order.total.gross == (total_gross_without_gift_cards - gift_cards_balance)
+
+
+ def test_create_order_with_gift_card_partial_use(
+ checkout_with_item, gift_card_used, customer_user, shipping_method
+ ):
+ checkout = checkout_with_item
+ checkout.user = customer_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.shipping_method = shipping_method
+ checkout.save()
+
- price_without_gift_card = checkout.get_total()
++ checkout_total = checkout.get_total()
++ price_without_gift_card = TaxedMoney(net=checkout_total, gross=checkout_total)
+ gift_card_balance_before_order = gift_card_used.current_balance
+
+ checkout.gift_cards.add(gift_card_used)
+ checkout.save()
+
+ order = create_order(
+ checkout=checkout,
+ order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
++ checkout=checkout, tracking_code="tracking_code", discounts=None
+ ),
+ user=customer_user,
+ )
+
+ gift_card_used.refresh_from_db()
+ assert order.gift_cards.count() > 0
+ assert order.total == ZERO_TAXED_MONEY
+ assert (
+ gift_card_balance_before_order
+ == (price_without_gift_card + gift_card_used.current_balance).gross.amount
+ )
+
+
+ def test_create_order_with_many_gift_cards(
+ checkout_with_item,
+ gift_card_created_by_staff,
+ gift_card,
+ customer_user,
+ shipping_method,
+ ):
+ checkout = checkout_with_item
+ checkout.user = customer_user
+ checkout.billing_address = customer_user.default_billing_address
+ checkout.shipping_address = customer_user.default_billing_address
+ checkout.shipping_method = shipping_method
+ checkout.save()
+
- price_without_gift_card = checkout.get_total()
++ checkout_total = checkout.get_total()
++ price_without_gift_card = TaxedMoney(net=checkout_total, gross=checkout_total)
+ gift_cards_balance_befor_order = (
+ gift_card_created_by_staff.current_balance + gift_card.current_balance
+ )
+
+ checkout.gift_cards.add(gift_card_created_by_staff)
+ checkout.gift_cards.add(gift_card)
+ checkout.save()
+
+ order = create_order(
+ checkout=checkout,
+ order_data=prepare_order_data(
- checkout=checkout, tracking_code="tracking_code", discounts=None, taxes=None
++ checkout=checkout, tracking_code="tracking_code", discounts=None
+ ),
+ user=customer_user,
+ )
+
+ gift_card_created_by_staff.refresh_from_db()
+ gift_card.refresh_from_db()
+ assert order.gift_cards.count() > 0
+ assert gift_card_created_by_staff.current_balance == ZERO_MONEY
+ assert gift_card.current_balance == ZERO_MONEY
+ assert price_without_gift_card.gross.amount == (
+ gift_cards_balance_befor_order + order.total.gross.amount
+ )
def test_note_in_created_order(request_checkout_with_item, address, customer_user):
@@@ -660,7 -812,14 +811,13 @@@
request_checkout_with_item.note = "test_note"
request_checkout_with_item.save()
order = create_order(
- request_checkout_with_item, "tracking_code", discounts=None, user=customer_user
+ checkout=request_checkout_with_item,
+ order_data=prepare_order_data(
+ checkout=request_checkout_with_item,
+ tracking_code="tracking_code",
+ discounts=None,
- taxes=None,
+ ),
+ user=customer_user,
)
assert order.customer_note == request_checkout_with_item.note
diff --cc tests/test_order.py
index 26e7ccdcb1,d6b29bf02b..f08bba65d3
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@@ -7,8 -8,13 +7,8 @@@ from prices import Money, TaxedMone
from saleor.account import events as account_events
from saleor.account.models import User
- from saleor.checkout.utils import create_order
+ from saleor.checkout.utils import create_order, prepare_order_data
from saleor.core.exceptions import InsufficientStock
-from saleor.core.utils.taxes import (
- DEFAULT_TAX_RATE_NAME,
- get_tax_rate_by_name,
- get_taxes_for_country,
-)
from saleor.core.weight import zero_weight
from saleor.order import FulfillmentStatus, OrderStatus, events as order_events, models
from saleor.order.models import Fulfillment, Order
@@@ -433,7 -459,14 +433,13 @@@ def test_order_payment_flow
request_checkout_with_item.save()
order = create_order(
- request_checkout_with_item, "tracking_code", discounts=None, user=customer_user
+ checkout=request_checkout_with_item,
+ order_data=prepare_order_data(
+ checkout=request_checkout_with_item,
+ tracking_code="tracking_code",
+ discounts=None,
- taxes=None,
+ ),
+ user=customer_user,
)
# Select payment