Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop country middleware (#6784)
Marcin Gębaladceb1dad09d1
diff --git a/.isort.cfg b/.isort.cfgindex 8b5a0f49ae..cb4ef6b8ff 100644--- a/.isort.cfg+++ b/.isort.cfg@@ -1,2 +1,2 @@[settings]-known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,geolite2,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,urllib3,versatileimagefield,weasyprint+known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,urllib3,versatileimagefield,weasyprintdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8418ffcff7..e020308ff7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ All notable, unreleased changes to this project will be documented in this file.- Drop `apply_taxes_to_shipping_price_range` plugin hook - #6746 by @maarcingebala- Drop `CHECKOUT_QUANTITY_CHANGED` webhook - #6797 by @d-wysocki- Drop deprecated `taxRate` field from `ProductType` - #6795 by @d-wysocki+- Remove resolving user's location from GeoIP; drop `PaymentInput.billingAddress` input field - #6784 by @maarcingebala### Otherdiff --git a/poetry.lock b/poetry.lockindex 3a57de79ed..1a8f60bfb3 100644--- a/poetry.lock+++ b/poetry.lock@@ -166,20 +166,20 @@ d = ["aiohttp (>=3.3.2)", "aiohttp-cors"][[package]]name = "boto3"-version = "1.17.4"+version = "1.17.5"description = "The AWS SDK for Python"category = "main"optional = falsepython-versions = ">= 2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"[package.dependencies]-botocore = ">=1.20.4,<1.21.0"+botocore = ">=1.20.5,<1.21.0"jmespath = ">=0.7.1,<1.0.0"s3transfer = ">=0.3.0,<0.4.0"[[package]]name = "botocore"-version = "1.20.4"+version = "1.20.5"description = "Low-level, data-driven core of boto 3."category = "main"optional = false@@ -780,7 +780,7 @@ testing = ["pre-commit"][[package]]name = "faker"-version = "6.0.0"+version = "6.1.1"description = "Faker is a Python package that generates fake data for you."category = "main"optional = false@@ -836,7 +836,7 @@ smmap = ">=3.0.1,<4"[[package]]name = "gitpython"-version = "3.1.12"+version = "3.1.13"description = "Python Git Library"category = "dev"optional = false@@ -1361,17 +1361,6 @@ category = "main"optional = falsepython-versions = ">=3.6"-[[package]]-name = "maxminddb-geolite2"-version = "2018.703"-description = "Provides access to the geolite2 database. This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com/"-category = "main"-optional = false-python-versions = "*"--[package.dependencies]-maxminddb = "*"-[[package]]name = "mccabe"version = "0.6.1"@@ -1393,12 +1382,16 @@ sympy = ">=0.7.3"[[package]]name = "mpmath"-version = "1.1.0"+version = "1.2.1"description = "Python library for arbitrary-precision floating-point arithmetic"category = "main"optional = falsepython-versions = "*"+[package.extras]+develop = ["pytest (>=4.6)", "pycodestyle", "pytest-cov", "codecov", "wheel"]+tests = ["pytest (>=4.6)"]+[[package]]name = "multidict"version = "5.1.0"@@ -2167,11 +2160,11 @@ python-versions = "*"[[package]]name = "soupsieve"-version = "2.1"+version = "2.2"description = "A modern CSS selector implementation for Beautiful Soup."category = "main"optional = false-python-versions = ">=3.5"+python-versions = ">=3.6"[[package]]name = "sqlparse"@@ -2293,7 +2286,7 @@ testing = ["flaky (>=3.4.0)", "freezegun (>=0.3.11)", "psutil (>=5.6.1)", "pytes[[package]]name = "tqdm"-version = "4.56.0"+version = "4.56.1"description = "Fast, Extensible Progress Meter"category = "main"optional = false@@ -2391,12 +2384,17 @@ standard = ["websockets (>=8.0.0,<9.0.0)", "watchgod (>=0.6,<0.7)", "python-dote[[package]]name = "uvloop"-version = "0.14.0"+version = "0.15.0"description = "Fast implementation of asyncio event loop on top of libuv"category = "main"optional = falsepython-versions = "*"+[package.extras]+dev = ["Cython (>=0.29.20,<0.30.0)", "pytest (>=3.6.0)", "Sphinx (>=1.7.3,<1.8.0)", "sphinxcontrib-asyncio (>=0.2.0,<0.3.0)", "sphinx-rtd-theme (>=0.2.4,<0.3.0)", "aiohttp", "flake8 (>=3.8.4,<3.9.0)", "psutil", "pycodestyle (>=2.6.0,<2.7.0)", "pyOpenSSL (>=19.0.0,<19.1.0)", "mypy (>=0.800)"]+docs = ["Sphinx (>=1.7.3,<1.8.0)", "sphinxcontrib-asyncio (>=0.2.0,<0.3.0)", "sphinx-rtd-theme (>=0.2.4,<0.3.0)"]+test = ["aiohttp", "flake8 (>=3.8.4,<3.9.0)", "psutil", "pycodestyle (>=2.6.0,<2.7.0)", "pyOpenSSL (>=19.0.0,<19.1.0)", "mypy (>=0.800)"]+[[package]]name = "vcrpy"version = "4.1.1"@@ -2514,7 +2512,7 @@ multidict = ">=4.0"[metadata]lock-version = "1.1"python-versions = "~3.9"-content-hash = "63f89dd275ac4835153f540cc042165b3d5bb6f71782d1e11152d9e73dd899d4"+content-hash = "6587173954a98d488801a647b476510ab94d978bd77e223615fe164e7ce247fa"[metadata.files]adyen = [@@ -2577,12 +2575,12 @@ black = [{file = "black-20.8b1.tar.gz", hash = "sha256:1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea"},]boto3 = [- {file = "boto3-1.17.4-py2.py3-none-any.whl", hash = "sha256:af87efaa772f95de67f72ed91aed2feef63593b5290696f669799202bc484b99"},- {file = "boto3-1.17.4.tar.gz", hash = "sha256:65514427f5f849245c9a272fa06a5a014ae3945333f4f407489d034fb99dc61f"},+ {file = "boto3-1.17.5-py2.py3-none-any.whl", hash = "sha256:0d126d429a8a9ea2c8409a1ee36ce5a34e11db788d7730a714016264f10bbb89"},+ {file = "boto3-1.17.5.tar.gz", hash = "sha256:d6aafb804fca2b67c65dda78ad8b4afed901e004071208b84c804d345ad9ebba"},]botocore = [- {file = "botocore-1.20.4-py2.py3-none-any.whl", hash = "sha256:96f9e0920ac91b6caae3039e5de09b80648ad57b4a97fc7d81a369afae34fb10"},- {file = "botocore-1.20.4.tar.gz", hash = "sha256:61657a1e4b3cdda9627084184bdf9dca4637c1523daead31a36974be0d51686d"},+ {file = "botocore-1.20.5-py2.py3-none-any.whl", hash = "sha256:3c55f0db5e08920727f4fa24a87aed60060643f4b0b5665c62ec762f79e82d6b"},+ {file = "botocore-1.20.5.tar.gz", hash = "sha256:04a1df759681f5f171accb354d863bfed0774d64a4e8ee35ff49835755660a4e"},]braintree = [{file = "braintree-4.6.0-py2.py3-none-any.whl", hash = "sha256:d3aa0e29eb3923574a58e8ee3219566c918ff161c98f2de715ba29cb715169c7"},@@ -2849,8 +2847,8 @@ execnet = [{file = "execnet-1.8.0.tar.gz", hash = "sha256:b73c5565e517f24b62dea8a5ceac178c661c4309d3aa0c3e420856c072c411b4"},]faker = [- {file = "Faker-6.0.0-py3-none-any.whl", hash = "sha256:190f0d3ce037866b5d230f0b9fd0f513f07c25dc326dcad6ee019849c68d441c"},- {file = "Faker-6.0.0.tar.gz", hash = "sha256:db7adc3b4755005fc960cf96fb4ed46b54b6eb21413741ab3f31a9595f379905"},+ {file = "Faker-6.1.1-py3-none-any.whl", hash = "sha256:bf2a9b3f8d00a5dada61fc4a3f80fe0d6795c7f02a138a7d2ef2db5817c7d017"},+ {file = "Faker-6.1.1.tar.gz", hash = "sha256:d4aecdb877519d06c2fdc01ffc5ecf70658981acf5e13cd07ded9892994ef5c6"},]filelock = [{file = "filelock-3.0.12-py3-none-any.whl", hash = "sha256:929b7d63ec5b7d6b71b0fa5ac14e030b3f70b75747cef1b10da9b879fef15836"},@@ -2869,8 +2867,8 @@ gitdb = [{file = "gitdb-4.0.5.tar.gz", hash = "sha256:c9e1f2d0db7ddb9a704c2a0217be31214e91a4fe1dea1efad19ae42ba0c285c9"},]gitpython = [- {file = "GitPython-3.1.12-py3-none-any.whl", hash = "sha256:867ec3dfb126aac0f8296b19fb63b8c4a399f32b4b6fafe84c4b10af5fa9f7b5"},- {file = "GitPython-3.1.12.tar.gz", hash = "sha256:42dbefd8d9e2576c496ed0059f3103dcef7125b9ce16f9d5f9c834aed44a1dac"},+ {file = "GitPython-3.1.13-py3-none-any.whl", hash = "sha256:c5347c81d232d9b8e7f47b68a83e5dc92e7952127133c5f2df9133f2c75a1b29"},+ {file = "GitPython-3.1.13.tar.gz", hash = "sha256:8621a7e777e276a5ec838b59280ba5272dd144a18169c36c903d8b38b99f750a"},]google-api-core = [{file = "google-api-core-1.26.0.tar.gz", hash = "sha256:4230ec764d48ca934fe69b85cc217e31e844e176f68df93e252acd55350e730b"},@@ -3185,9 +3183,6 @@ markupsafe = [maxminddb = [{file = "maxminddb-2.0.3.tar.gz", hash = "sha256:47e86a084dd814fac88c99ea34ba3278a74bc9de5a25f4b815b608798747c7dc"},]-maxminddb-geolite2 = [- {file = "maxminddb-geolite2-2018.703.tar.gz", hash = "sha256:2bd118c5567f3a8323d6c5da23a6e6d52cfc09cd9987b54eb712cf6001a96e03"},-]mccabe = [{file = "mccabe-0.6.1-py2.py3-none-any.whl", hash = "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42"},{file = "mccabe-0.6.1.tar.gz", hash = "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f"},@@ -3196,7 +3191,8 @@ measurement = [{file = "measurement-3.2.0.tar.gz", hash = "sha256:352b20f7f0e553236af7c5ed48d091a51cf26061c1a063f46b31706ff7c0d57a"},]mpmath = [- {file = "mpmath-1.1.0.tar.gz", hash = "sha256:fc17abe05fbab3382b61a123c398508183406fa132e0223874578e20946499f6"},+ {file = "mpmath-1.2.1-py3-none-any.whl", hash = "sha256:604bc21bd22d2322a177c73bdb573994ef76e62edd595d17e00aff24b0667e5c"},+ {file = "mpmath-1.2.1.tar.gz", hash = "sha256:79ffb45cf9f4b101a807595bcb3e72e0396202e0b1d25d689134b48c4216a81a"},]multidict = [{file = "multidict-5.1.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:b7993704f1a4b204e71debe6095150d43b2ee6150fa4f44d6d966ec356a8d61f"},@@ -3657,8 +3653,8 @@ snowballstemmer = [{file = "snowballstemmer-2.1.0.tar.gz", hash = "sha256:e997baa4f2e9139951b6f4c631bad912dfd3c792467e2f03d7239464af90e914"},]soupsieve = [- {file = "soupsieve-2.1-py3-none-any.whl", hash = "sha256:4bb21a6ee4707bf43b61230e80740e71bfe56e55d1f1f50924b087bb2975c851"},- {file = "soupsieve-2.1.tar.gz", hash = "sha256:6dc52924dc0bc710a5d16794e6b3480b2c7c08b07729505feab2b2c16661ff6e"},+ {file = "soupsieve-2.2-py3-none-any.whl", hash = "sha256:d3a5ea5b350423f47d07639f74475afedad48cf41c0ad7a82ca13a3928af34f6"},+ {file = "soupsieve-2.2.tar.gz", hash = "sha256:407fa1e8eb3458d1b5614df51d9651a1180ea5fedf07feb46e45d7e25e6d6cdd"},]sqlparse = [{file = "sqlparse-0.4.1-py3-none-any.whl", hash = "sha256:017cde379adbd6a1f15a61873f43e8274179378e95ef3fede90b5aa64d304ed0"},@@ -3739,8 +3735,8 @@ tox = [{file = "tox-3.21.4.tar.gz", hash = "sha256:cf7fef81a3a2434df4d7af2a6d1bf606d2970220addfbe7dea2615bd4bb2c252"},]tqdm = [- {file = "tqdm-4.56.0-py2.py3-none-any.whl", hash = "sha256:4621f6823bab46a9cc33d48105753ccbea671b68bab2c50a9f0be23d4065cb5a"},- {file = "tqdm-4.56.0.tar.gz", hash = "sha256:fe3d08dd00a526850568d542ff9de9bbc2a09a791da3c334f3213d8d0bbbca65"},+ {file = "tqdm-4.56.1-py2.py3-none-any.whl", hash = "sha256:ab9b659241d82b8b51b2269ee243ec95286046bf06015c4e15a947cc15914211"},+ {file = "tqdm-4.56.1.tar.gz", hash = "sha256:2874fa525c051177583ec59c0fb4583e91f28ccd3f217ffad2acdb32d2c789ac"},]transifex-client = [{file = "transifex-client-0.14.2.tar.gz", hash = "sha256:b458c56d6d07d2d8269b43d5049026304ed9a34d31bdf655d9e1864807e7555b"},@@ -3800,15 +3796,16 @@ uvicorn = [{file = "uvicorn-0.13.3.tar.gz", hash = "sha256:ef1e0bb5f7941c6fe324e06443ddac0331e1632a776175f87891c7bd02694355"},]uvloop = [- {file = "uvloop-0.14.0-cp35-cp35m-macosx_10_11_x86_64.whl", hash = "sha256:08b109f0213af392150e2fe6f81d33261bb5ce968a288eb698aad4f46eb711bd"},- {file = "uvloop-0.14.0-cp35-cp35m-manylinux2010_x86_64.whl", hash = "sha256:4544dcf77d74f3a84f03dd6278174575c44c67d7165d4c42c71db3fdc3860726"},- {file = "uvloop-0.14.0-cp36-cp36m-macosx_10_11_x86_64.whl", hash = "sha256:b4f591aa4b3fa7f32fb51e2ee9fea1b495eb75b0b3c8d0ca52514ad675ae63f7"},- {file = "uvloop-0.14.0-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:f07909cd9fc08c52d294b1570bba92186181ca01fe3dc9ffba68955273dd7362"},- {file = "uvloop-0.14.0-cp37-cp37m-macosx_10_11_x86_64.whl", hash = "sha256:afd5513c0ae414ec71d24f6f123614a80f3d27ca655a4fcf6cabe50994cc1891"},- {file = "uvloop-0.14.0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:e7514d7a48c063226b7d06617cbb12a14278d4323a065a8d46a7962686ce2e95"},- {file = "uvloop-0.14.0-cp38-cp38-macosx_10_11_x86_64.whl", hash = "sha256:bcac356d62edd330080aed082e78d4b580ff260a677508718f88016333e2c9c5"},- {file = "uvloop-0.14.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:4315d2ec3ca393dd5bc0b0089d23101276778c304d42faff5dc4579cb6caef09"},- {file = "uvloop-0.14.0.tar.gz", hash = "sha256:123ac9c0c7dd71464f58f1b4ee0bbd81285d96cdda8bc3519281b8973e3a461e"},+ {file = "uvloop-0.15.0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:e17cc3f32288daf8476368ddb60cad0f00ab13c979f6f4003ee773f1d90cab58"},+ {file = "uvloop-0.15.0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:9ae0b0e86ffcfe11c208fdb1552894911aa0915280e904a3757ebd4505792568"},+ {file = "uvloop-0.15.0-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:9900020313c158cbc7befdd5ad60eb7b5443d7d1e83ad57c310e330fe7b2d858"},+ {file = "uvloop-0.15.0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:1c114eafd3c53cab74024d122742ed9001611e8f341421dba84a8ea7d886cc2f"},+ {file = "uvloop-0.15.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:08547ec0d40005da5c5f969f406cc90e6d589b41388958e326d78ea63fb5d2f9"},+ {file = "uvloop-0.15.0-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:cb121716f4ff5c01dd9b9a12b2193e59383243c21d14c916f588fd626bd3c74b"},+ {file = "uvloop-0.15.0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:ad5391ce33ac1c745dec6f8a394387b3247c374e93b12a1f0403791f6be4bb8a"},+ {file = "uvloop-0.15.0-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:fab95c88d0c3694089c93a8c46fdab30117c4ce0d1afa2ab7d6f4d0607495857"},+ {file = "uvloop-0.15.0-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:2d76da5529025f9771855505cfde7bf16b9b0001e2fe05b0abf3e4fc01a5dfdb"},+ {file = "uvloop-0.15.0.tar.gz", hash = "sha256:1a503d5b49da6e3dd5607d6e533a5315b1caedbf629901807c65a23a09cad065"},]vcrpy = [{file = "vcrpy-4.1.1-py2.py3-none-any.whl", hash = "sha256:12c3fcdae7b88ecf11fc0d3e6d77586549d4575a2ceee18e82eee75c1f626162"},diff --git a/pyproject.toml b/pyproject.tomlindex 3404972136..9c7b2c11e6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,7 +42,6 @@ graphene-federation = "^0.1.0"html-to-draftjs = "^1.0.1"markdown = "^3.1.1"maxminddb = ">=1.5.4,<3.0.0"-maxminddb-geolite2 = "^2018.701"petl = "1.7.2"opentracing = "^2.3.0"phonenumberslite = "^8.12.6"diff --git a/requirements.txt b/requirements.txtindex 8e51f78333..2bb425d486 100644--- a/requirements.txt+++ b/requirements.txt@@ -78,7 +78,6 @@ kombu==5.0.2; python_version >= "3.6"libcst==0.3.17; python_version >= "3.6"lxml==4.6.2; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0"markdown==3.3.3; python_version >= "3.6"-maxminddb-geolite2==2018.703maxminddb==2.0.3; python_version >= "3.6"measurement==3.2.0mpmath==1.1.0; python_version >= "3.6"diff --git a/requirements_dev.txt b/requirements_dev.txtindex 5bef17c2aa..2f5b0e9950 100644--- a/requirements_dev.txt+++ b/requirements_dev.txt@@ -105,7 +105,6 @@ libcst==0.3.17; python_version >= "3.6"lxml==4.6.2; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0"markdown==3.3.3; python_version >= "3.6"markupsafe==1.1.1; python_version >= "2.7" and python_full_version < "3.0.0" or python_full_version >= "3.5.0"-maxminddb-geolite2==2018.703maxminddb==2.0.3; python_version >= "3.6"mccabe==0.6.1; python_version >= "3.5" and python_full_version < "3.0.0" or python_full_version >= "3.4.0" and python_version >= "3.5"measurement==3.2.0diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex 9819e6f9cb..2b03ad84fe 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -7,13 +7,11 @@ from django.core.exceptions import MiddlewareNotUsedfrom django.utils import timezonefrom django.utils.functional import SimpleLazyObjectfrom django.utils.translation import get_language-from django_countries.fields import Countryfrom ..discount.utils import fetch_discountsfrom ..plugins.manager import get_plugins_managerfrom . import analyticsfrom .jwt import JWT_REFRESH_TOKEN_COOKIE_NAME, jwt_decode_with_exception_handler-from .utils import get_client_ip, get_country_by_ip, get_currency_for_countrylogger = logging.getLogger(__name__)@@ -60,31 +58,6 @@ def discounts(get_response):return _discounts_middleware-def country(get_response):- """Detect the user's country and assign it to `request.country`."""-- def _country_middleware(request):- client_ip = get_client_ip(request)- if client_ip:- request.country = get_country_by_ip(client_ip)- if not request.country:- request.country = Country(settings.DEFAULT_COUNTRY)- return get_response(request)-- return _country_middleware---def currency(get_response):- """Take a country and assign a matching currency to `request.currency`."""-- def _currency_middleware(request):- if hasattr(request, "country") and request.country is not None:- request.currency = get_currency_for_country(request.country)- return get_response(request)-- return _currency_middleware--def site(get_response):"""Clear the Sites cache and assign the current site to `request.site`.diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.pyindex 4a3cf10605..853fb2d312 100644--- a/saleor/core/tests/test_core.py+++ b/saleor/core/tests/test_core.py@@ -8,6 +8,7 @@ from django.core.management import CommandError, call_commandfrom django.db.utils import DataErrorfrom django.templatetags.static import staticfrom django.test import RequestFactory, override_settings+from django_countries.fields import Countryfrom ...account.models import Address, Userfrom ...account.utils import create_superuser@@ -20,12 +21,10 @@ from ...shipping.models import ShippingZonefrom ..storages import S3MediaStoragefrom ..templatetags.placeholder import placeholderfrom ..utils import (- Country,build_absolute_uri,create_thumbnails,generate_unique_slug,get_client_ip,- get_country_by_ip,get_currency_for_country,random_data,)@@ -44,24 +43,6 @@ type_schema = {}- "ip_data, expected_country",- [- ({"country": {"iso_code": "PL"}}, Country("PL")),- ({"country": {"iso_code": "UNKNOWN"}}, None),- (None, None),- ({}, None),- ({"country": {}}, None),- ],-)-def test_get_country_by_ip(ip_data, expected_country, monkeypatch):- monkeypatch.setattr(- "saleor.core.utils._get_geo_data_by_ip", Mock(return_value=ip_data)- )- country = get_country_by_ip("127.0.0.1")- assert country == expected_country--@pytest.mark.parametrize("ip_address, expected_ip",[@@ -88,7 +69,7 @@ def test_get_client_ip(ip_address, expected_ip):[(Country("PL"), "PLN"), (Country("US"), "USD"), (Country("GB"), "GBP")],)def test_get_currency_for_country(country, expected_currency, monkeypatch):- currency = get_currency_for_country(country)+ currency = get_currency_for_country(country.code)assert currency == expected_currencydiff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex 3da46af46a..1861c8cc8c 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -10,14 +10,10 @@ from django.contrib.sites.models import Sitefrom django.db.models import Modelfrom django.utils.encoding import iri_to_urifrom django.utils.text import slugify-from django_countries import countries-from django_countries.fields import Countryfrom django_prices_openexchangerates import exchange_currency-from geolite2 import geolite2from prices import MoneyRangefrom versatileimagefield.image_warmer import VersatileImageFieldWarmer-georeader = geolite2.reader()logger = logging.getLogger(__name__)@@ -74,24 +70,8 @@ def is_valid_ipv6(ip: str) -> bool:return True-def _get_geo_data_by_ip(ip_address):- # This function is here to make it easier to mock the GeoIP- # as the georeader object below can be a native platform library- # that does not support monkeypatching.- return georeader.get(ip_address)---def get_country_by_ip(ip_address):- geo_data = _get_geo_data_by_ip(ip_address)- if geo_data and "country" in geo_data and "iso_code" in geo_data["country"]:- country_iso_code = geo_data["country"]["iso_code"]- if country_iso_code in countries:- return Country(country_iso_code)- return None---def get_currency_for_country(country):- currencies = get_territory_currencies(country.code)+def get_currency_for_country(country_code: str):+ currencies = get_territory_currencies(country_code)if currencies:return currencies[0]return os.environ.get("DEFAULT_CURRENCY", "USD")diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex b0b3cc130c..5665f4e791 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -90,6 +90,8 @@ PRODUCTS_LIST_DIR = "products-list/"DUMMY_STAFF_PASSWORD = "password"+DEFAULT_CURRENCY = os.environ.get("DEFAULT_CURRENCY", "USD")+IMAGES_MAPPING = {61: ["saleordemoproduct_paints_01.png"],62: ["saleordemoproduct_paints_02.png"],@@ -386,7 +388,7 @@ def assign_attributes_to_pages(page_attributes):def set_field_as_money(defaults, field):amount_field = f"{field}_amount"if amount_field in defaults and defaults[amount_field] is not None:- defaults[field] = Money(defaults[amount_field], settings.DEFAULT_CURRENCY)+ defaults[field] = Money(defaults[amount_field], DEFAULT_CURRENCY)def create_products_by_schema(placeholder_dir, create_images):@@ -450,7 +452,7 @@ def create_products_by_schema(placeholder_dir, create_images):class SaleorProvider(BaseProvider):def money(self):- return Money(fake.pydecimal(2, 2, positive=True), settings.DEFAULT_CURRENCY)+ return Money(fake.pydecimal(2, 2, positive=True), DEFAULT_CURRENCY)def weight(self):return Weight(kg=fake.pydecimal(1, 2, positive=True))@@ -1261,8 +1263,8 @@ def create_gift_card():code="Gift_card_10",defaults={"user": user,- "initial_balance": Money(10, settings.DEFAULT_CURRENCY),- "current_balance": Money(10, settings.DEFAULT_CURRENCY),+ "initial_balance": Money(10, DEFAULT_CURRENCY),+ "current_balance": Money(10, DEFAULT_CURRENCY),},)if created:diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 8ecb01df31..521537b21f 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -39,6 +39,7 @@ from ..core.utils import from_global_id_strict_typefrom ..order.types import Orderfrom ..product.types import ProductVariantfrom ..shipping.types import ShippingMethod+from ..utils import get_user_country_contextfrom .types import Checkout, CheckoutLineERROR_DOES_NOT_SHIP = "This checkout doesn't need shipping"@@ -286,19 +287,18 @@ class CheckoutCreate(ModelMutation, I18nMixin):@classmethoddef clean_input(cls, info, instance: models.Checkout, data, input_cls=None):user = info.context.user- country = info.context.country.codechannel = data.pop("channel")cleaned_input = super().clean_input(info, instance, data)cleaned_input["channel"] = channelcleaned_input["currency"] = channel.currency_code- # set country to one from shipping address- shipping_address = cleaned_input.get("shipping_address")- if shipping_address and shipping_address.country:- if shipping_address.country != country:- country = shipping_address.country- cleaned_input["country"] = country+ shipping_address = cls.retrieve_shipping_address(user, data)+ billing_address = cls.retrieve_billing_address(user, data)+ country = get_user_country_context(+ destination_address=shipping_address,+ company_address=info.context.site.settings.company_address,+ )# Resolve and process the lines, retrieving the variants and quantitieslines = data.pop("lines", None)@@ -308,14 +308,14 @@ class CheckoutCreate(ModelMutation, I18nMixin):cleaned_input["quantities"],) = cls.clean_checkout_lines(lines, country, cleaned_input["channel"].id)- cleaned_input["shipping_address"] = cls.retrieve_shipping_address(user, data)- cleaned_input["billing_address"] = cls.retrieve_billing_address(user, data)-# Use authenticated user's email as default emailif user.is_authenticated:email = data.pop("email", None)cleaned_input["email"] = email or user.email+ cleaned_input["shipping_address"] = shipping_address+ cleaned_input["billing_address"] = billing_address+ cleaned_input["country"] = countryreturn cleaned_input@classmethod@@ -632,11 +632,10 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):lines = fetch_checkout_lines(checkout)- country = info.context.country.code- # set country to one from shipping address- if shipping_address and shipping_address.country:- if shipping_address.country != country:- country = shipping_address.country+ country = get_user_country_context(+ destination_address=shipping_address,+ company_address=info.context.site.settings.company_address,+ )checkout.set_country(country, commit=True)# Resolve and process the lines, validating variants quantitiesdiff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex 418998af4b..2dbdc426c0 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -11,7 +11,6 @@ from ...payment import PaymentError, gatewayfrom ...payment.error_codes import PaymentErrorCodefrom ...payment.utils import create_payment, is_currency_supportedfrom ..account.i18n import I18nMixin-from ..account.types import AddressInputfrom ..checkout.types import Checkoutfrom ..core.mutations import BaseMutationfrom ..core.scalars import PositiveDecimal@@ -40,15 +39,6 @@ class PaymentInput(graphene.InputObjectType):"the checkout total will be used."),)- billing_address = AddressInput(- required=False,- description=(- "[Deprecated] Billing address. If empty, the billing address associated "- "with the checkout instance will be used. Use `checkoutCreate` or "- "`checkoutBillingAddressUpdate` mutations to set it. This field will be "- "removed after 2020-07-31."- ),- )return_url = graphene.String(required=False,description=(@@ -74,18 +64,6 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):error_type_class = common_types.PaymentErrorerror_type_field = "payment_errors"- @classmethod- def clean_shipping_method(cls, checkout):- if not checkout.shipping_method:- raise ValidationError(- {- "shipping_method": ValidationError(- "Shipping method not set for this checkout.",- code=PaymentErrorCode.SHIPPING_METHOD_NOT_SET,- )- }- )-@classmethoddef clean_payment_amount(cls, info, checkout_total, amount):if amount != checkout_total.gross.amount:diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex ea7c5cbcbe..ad695bce86 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -1357,9 +1357,9 @@ def test_fetch_product_from_category_query(category = Category.objects.first()product = category.products.first()query = """- query {- category(id: "%(category_id)s") {- products(first: 20, channel: "%(channel_slug)s") {+ query CategoryProducts($id: ID, $channel: String, $address: AddressInput) {+ category(id: $id) {+ products(first: 20, channel: $channel) {edges {node {id@@ -1395,8 +1395,8 @@ def test_fetch_product_from_category_query(stop}}- isAvailable- pricing {+ isAvailable(address: $address)+ pricing(address: $address) {priceRange {start {gross {@@ -1418,12 +1418,14 @@ def test_fetch_product_from_category_query(}}}- """ % {- "category_id": graphene.Node.to_global_id("Category", category.id),- "channel_slug": channel_USD.slug,- }+ """staff_api_client.user.user_permissions.add(permission_manage_products)- response = staff_api_client.post_graphql(query)+ variables = {+ "id": graphene.Node.to_global_id("Category", category.id),+ "channel": channel_USD.slug,+ "address": {"country": "US"},+ }+ response = staff_api_client.post_graphql(query, variables)content = get_graphql_content(response)assert content["data"]["category"] is not Noneproduct_edges_data = content["data"]["category"]["products"]["edges"]@@ -6355,10 +6357,10 @@ def test_product_variant_price().update(price_amount=variant_price_amount)query = """- query getProductVariants($id: ID!, $channel: String) {+ query getProductVariants($id: ID!, $channel: String, $address: AddressInput) {product(id: $id, channel: $channel) {variants {- pricing {+ pricing(address: $address) {priceUndiscounted {gross {amount@@ -6370,7 +6372,11 @@ def test_product_variant_price(}"""product_id = graphene.Node.to_global_id("Product", variant.product.id)- variables = {"id": product_id, "channel": channel_USD.slug}+ variables = {+ "id": product_id,+ "channel": channel_USD.slug,+ "address": {"country": "US"},+ }response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)data = content["data"]["product"]diff --git a/saleor/graphql/product/tests/test_product_channel_listings_queries.py b/saleor/graphql/product/tests/test_product_channel_listings_queries.pyindex e30c5bcd66..ad5b65a583 100644--- a/saleor/graphql/product/tests/test_product_channel_listings_queries.py+++ b/saleor/graphql/product/tests/test_product_channel_listings_queries.py@@ -3,10 +3,10 @@ import graphenefrom ...tests.utils import get_graphql_contentQUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING = """-query FetchProduct($id: ID, $channel: String) {+query FetchProduct($id: ID, $channel: String, $address: AddressInput) {product(id: $id, channel: $channel) {id- pricing {+ pricing(address: $address) {priceRangeUndiscounted {start {gross {@@ -26,7 +26,7 @@ query FetchProduct($id: ID, $channel: String) {channel {slug}- pricing {+ pricing(address: $address) {priceRangeUndiscounted {start {gross {@@ -55,6 +55,7 @@ def test_product_channel_listing_pricing_field(variables = {"id": graphene.Node.to_global_id("Product", product.pk),"channel": channel_USD.slug,+ "address": {"country": "US"},}product.channel_listings.exclude(channel__slug=channel_USD.slug).delete()diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 2eb548b49d..0a9eb9b133 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -29,10 +29,15 @@ def test_fetch_variant(channel_USD,):query = """- query ProductVariantDetails($id: ID!, $countyCode: CountryCode, $channel: String) {+ query ProductVariantDetails(+ $id: ID!, $address: AddressInput, $countryCode: CountryCode, $channel: String+ ) {productVariant(id: $id, channel: $channel) {id- stocks(countryCode: $countyCode) {+ deprecatedStocksByCountry: stocks(countryCode: $countryCode) {+ id+ }+ stocksByAddress: stocks(address: $address) {id}attributes {@@ -92,7 +97,7 @@ def test_fetch_variant(site_settings.save(update_fields=["default_weight_unit"])variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- variables = {"id": variant_id, "countyCode": "EU", "channel": channel_USD.slug}+ variables = {"id": variant_id, "countryCode": "EU", "channel": channel_USD.slug}staff_api_client.user.user_permissions.add(permission_manage_products)# when@@ -102,7 +107,11 @@ def test_fetch_variant(content = get_graphql_content(response)data = content["data"]["productVariant"]assert data["name"] == variant.name- assert len(data["stocks"]) == variant.stocks.count()++ stocks_count = variant.stocks.count()+ assert len(data["deprecatedStocksByCountry"]) == stocks_count+ assert len(data["stocksByAddress"]) == stocks_count+assert data["weight"]["value"] == 10000assert data["weight"]["unit"] == WeightUnitsEnum.G.namechannel_listing_data = data["channelListings"][0]diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.pyindex e9bb197686..d565c382cb 100644--- a/saleor/graphql/product/tests/test_variant_availability.py+++ b/saleor/graphql/product/tests/test_variant_availability.py@@ -27,9 +27,12 @@ def test_variant_quantity_available_without_country_code(QUERY_VARIANT_AVAILABILITY = """- query variantAvailability($id: ID!, $country: CountryCode, $channel: String) {+ query variantAvailability(+ $id: ID!, $country: CountryCode, $address: AddressInput, $channel: String+ ) {productVariant(id: $id, channel: $channel) {- quantityAvailable(countryCode: $country)+ deprecatedByCountry: quantityAvailable(countryCode: $country)+ byAddress: quantityAvailable(address: $address)}}"""@@ -40,13 +43,14 @@ def test_variant_quantity_available_with_country_code():variables = {"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),- "country": COUNTRY_CODE,+ "address": {"country": COUNTRY_CODE},"channel": channel_USD.slug,}response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == 7+ assert variant_data["deprecatedByCountry"] == 7+ assert variant_data["byAddress"] == 7def test_variant_quantity_available_with_null_as_country_code(@@ -60,7 +64,8 @@ def test_variant_quantity_available_with_null_as_country_code(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == 7+ assert variant_data["deprecatedByCountry"] == 7+ assert variant_data["byAddress"] == 7@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)@@ -78,7 +83,8 @@ def test_variant_quantity_available_with_max(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITYdef test_variant_quantity_available_without_stocks(@@ -93,7 +99,8 @@ def test_variant_quantity_available_without_stocks(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == 0+ assert variant_data["deprecatedByCountry"] == 0+ assert variant_data["byAddress"] == 0def test_variant_quantity_available_with_allocations(@@ -111,7 +118,8 @@ def test_variant_quantity_available_with_allocations(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == 3+ assert variant_data["deprecatedByCountry"] == 3+ assert variant_data["byAddress"] == 3@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)@@ -128,7 +136,8 @@ def test_variant_quantity_available_without_inventory_tracking(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITY@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)@@ -145,4 +154,5 @@ def test_variant_quantity_available_without_inventory_tracking_and_stocks(response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]- assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["deprecatedByCountry"] == settings.MAX_CHECKOUT_LINE_QUANTITY+ assert variant_data["byAddress"] == settings.MAX_CHECKOUT_LINE_QUANTITYdiff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.pyindex f800f29729..b9d29bb7d8 100644--- a/saleor/graphql/product/tests/test_variant_pricing.py+++ b/saleor/graphql/product/tests/test_variant_pricing.py@@ -8,12 +8,12 @@ from ....product.utils.availability import get_variant_availabilityfrom ...tests.utils import get_graphql_contentQUERY_GET_VARIANT_PRICING = """-query ($channel: String) {+query ($channel: String, $address: AddressInput) {products(first: 1, channel: $channel) {edges {node {variants {- pricing {+ pricing(address: $address) {onSalediscount {currency@@ -47,9 +47,8 @@ def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):sale_discounted_value = sale.channel_listings.get().discount_valuediscounted_price = price.amount - sale_discounted_value- response = api_client.post_graphql(- QUERY_GET_VARIANT_PRICING, {"channel": channel_USD.slug}- )+ variables = {"channel": channel_USD.slug, "address": {"country": "US"}}+ response = api_client.post_graphql(QUERY_GET_VARIANT_PRICING, variables)content = get_graphql_content(response)pricing = content["data"]["products"]["edges"][0]["node"]["variants"][0]["pricing"]@@ -76,9 +75,8 @@ def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):def test_get_variant_pricing_not_on_sale(api_client, product, channel_USD):price = product.variants.first().channel_listings.get().price- response = api_client.post_graphql(- QUERY_GET_VARIANT_PRICING, {"channel": channel_USD.slug}- )+ variables = {"channel": channel_USD.slug, "address": {"country": "US"}}+ response = api_client.post_graphql(QUERY_GET_VARIANT_PRICING, variables)content = get_graphql_content(response)pricing = content["data"]["products"]["edges"][0]["node"]["variants"][0]["pricing"]diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex e1a84d671a..34394e8307 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -5,6 +5,7 @@ import graphenefrom saleor.graphql.product.dataloaders.products import ProductByIdLoaderfrom ....core.permissions import ProductPermissions+from ....core.utils import get_currency_for_countryfrom ....graphql.core.types import Money, MoneyRangefrom ....product import modelsfrom ....product.utils.availability import get_product_availability@@ -12,10 +13,12 @@ from ....product.utils.costs import (get_margin_for_variant_channel_listing,get_product_costs_data,)+from ...account import types as account_typesfrom ...channel.dataloaders import ChannelByIdLoaderfrom ...core.connection import CountableDjangoObjectTypefrom ...decorators import permission_requiredfrom ...discount.dataloaders import DiscountsByDateTimeLoader+from ...utils import get_user_country_contextfrom ..dataloaders import (CollectionsByProductIdLoader,ProductVariantsByProductIdLoader,@@ -40,6 +43,15 @@ class ProductChannelListing(CountableDjangoObjectType):)pricing = graphene.Field("saleor.graphql.product.types.products.ProductPricingInfo",+ address=graphene.Argument(+ account_types.AddressInput,+ description=(+ "Destination address used to find warehouses where stock availability "+ "for this product is checked. If address is empty, uses "+ "`Shop.companyAddress` or fallbacks to server's "+ "`settings.DEFAULT_COUNTRY` configuration."+ ),+ ),description=("Lists the storefront product's pricing, the current price and discounts, ""only meant for displaying."@@ -142,8 +154,11 @@ class ProductChannelListing(CountableDjangoObjectType):return root.is_available_for_purchase()@staticmethod- def resolve_pricing(root: models.ProductChannelListing, info):+ def resolve_pricing(root: models.ProductChannelListing, info, address=None):context = info.context+ country_code = get_user_country_context(+ address, info.context.site.settings.company_address+ )def calculate_pricing_info(discounts):def calculate_pricing_with_channel(channel):@@ -163,8 +178,10 @@ class ProductChannelListing(CountableDjangoObjectType):collections=collections,discounts=discounts,channel=channel,- country=context.country,- local_currency=context.currency,+ country=country_code,+ local_currency=get_currency_for_country(+ country_code+ ),plugins=context.plugins,)from .products import ProductPricingInfodiff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex bb97b6869c..4b8117ba96 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -10,6 +10,7 @@ from graphql.error import GraphQLErrorfrom ....account.utils import requestor_is_staff_member_or_appfrom ....attribute import models as attribute_modelsfrom ....core.permissions import OrderPermissions, ProductPermissions+from ....core.utils import get_currency_for_countryfrom ....core.weight import convert_weight_to_default_weight_unitfrom ....product import modelsfrom ....product.templatetags.product_images import (@@ -23,6 +24,7 @@ from ....product.utils.availability import ()from ....product.utils.variants import get_variant_selection_attributesfrom ....warehouse.availability import is_product_in_stock+from ...account import types as account_typesfrom ...account.enums import CountryCodeEnumfrom ...attribute.filters import AttributeFilterInputfrom ...attribute.resolvers import resolve_attributes@@ -57,7 +59,11 @@ from ...translations.types import (ProductTranslation,ProductVariantTranslation,)-from ...utils import get_database_id, get_user_or_app_from_context+from ...utils import (+ get_database_id,+ get_user_country_context,+ get_user_or_app_from_context,+)from ...utils.filters import reporting_period_to_datefrom ...warehouse.dataloaders import (AvailableQuantityByProductVariantIdAndCountryCodeLoader,@@ -94,6 +100,16 @@ from .channels import ()from .digital_contents import DigitalContent+destination_address_argument = graphene.Argument(+ account_types.AddressInput,+ description=(+ "Destination address used to find warehouses where stock availability "+ "for this product is checked. If address is empty, uses "+ "`Shop.companyAddress` or fallbacks to server's "+ "`settings.DEFAULT_COUNTRY` configuration."+ ),+)+class Margin(graphene.ObjectType):start = graphene.Int()@@ -157,6 +173,7 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):)pricing = graphene.Field(VariantPricingInfo,+ address=destination_address_argument,description=("Lists the storefront variant's pricing, the current price and discounts, ""only meant for displaying."@@ -197,18 +214,24 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):stocks = graphene.Field(graphene.List(Stock),description="Stocks for the product variant.",+ address=destination_address_argument,country_code=graphene.Argument(CountryCodeEnum,- description="Two-letter ISO 3166-1 country code.",- required=False,+ description=(+ "DEPRECATED: use `address` argument instead. This argument will be "+ "removed in Saleor 4.0. Two-letter ISO 3166-1 country code."+ ),),)quantity_available = graphene.Int(required=True,description="Quantity of a product available for sale in one checkout.",+ address=destination_address_argument,country_code=graphene.Argument(CountryCodeEnum,description=(+ "DEPRECATED: use `address` argument instead. This argument will be "+ "removed in Saleor 4.0.""Two-letter ISO 3166-1 country code. When provided, the exact quantity ""from a warehouse operating in shipping zones that contain this ""country will be returned. Otherwise, it will return the maximum "@@ -231,16 +254,32 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):[ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS])def resolve_stocks(- root: ChannelContext[models.ProductVariant], info, country_code=None+ root: ChannelContext[models.ProductVariant],+ info,+ address=None,+ country_code=None,):+ if address is not None:+ country_code = get_user_country_context(+ address, info.context.site.settings.company_address+ )+if not country_code:return root.node.stocks.annotate_available_quantity()return root.node.stocks.for_country(country_code).annotate_available_quantity()@staticmethoddef resolve_quantity_available(- root: ChannelContext[models.ProductVariant], info, country_code=None+ root: ChannelContext[models.ProductVariant],+ info,+ address=None,+ country_code=None,):+ if address is not None:+ country_code = get_user_country_context(+ address, info.context.site.settings.company_address+ )+if not root.node.track_inventory:return settings.MAX_CHECKOUT_LINE_QUANTITY@@ -293,12 +332,19 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return VariantChannelListingByVariantIdLoader(info.context).load(root.node.id)@staticmethod- def resolve_pricing(root: ChannelContext[models.ProductVariant], info):+ def resolve_pricing(+ root: ChannelContext[models.ProductVariant], info, address=None+ ):if not root.channel_slug:return None+ country_code = get_user_country_context(+ address, info.context.site.settings.company_address+ )+channel_slug = str(root.channel_slug)context = info.context+product = ProductByIdLoader(context).load(root.node.product_id)product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(context@@ -332,8 +378,10 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):collections=collections,discounts=discounts,channel=channel,- country=context.country,- local_currency=context.currency,+ country=country_code,+ local_currency=get_currency_for_country(+ country_code+ ),plugins=context.plugins,)return VariantPricingInfo(**asdict(availability))@@ -448,13 +496,15 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):)pricing = graphene.Field(ProductPricingInfo,+ address=destination_address_argument,description=("Lists the storefront product's pricing, the current price and discounts, ""only meant for displaying."),)is_available = graphene.Boolean(- description="Whether the product is in stock and visible or not."+ address=destination_address_argument,+ description="Whether the product is in stock and visible or not.",)tax_type = graphene.Field(TaxType, description="A type of tax. Assigned by enabled tax gateway"@@ -567,10 +617,13 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):return ""@staticmethod- def resolve_pricing(root: ChannelContext[models.Product], info):+ def resolve_pricing(root: ChannelContext[models.Product], info, address=None):if not root.channel_slug:return None+ country_code = get_user_country_context(+ address, info.context.site.settings.company_address+ )context = info.contextchannel_slug = str(root.channel_slug)product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(@@ -603,8 +656,10 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):collections=collections,discounts=discounts,channel=channel,- country=context.country,- local_currency=context.currency,+ country=country_code,+ local_currency=get_currency_for_country(+ country_code+ ),plugins=context.plugins,)return ProductPricingInfo(**asdict(availability))@@ -630,14 +685,17 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):)@staticmethod- def resolve_is_available(root: ChannelContext[models.Product], info):+ def resolve_is_available(root: ChannelContext[models.Product], info, address=None):if not root.channel_slug:return None+channel_slug = str(root.channel_slug)+ country_code = get_user_country_context(+ address, info.context.site.settings.company_address+ )def calculate_is_available(product_channel_listing):- country = info.context.country- in_stock = is_product_in_stock(root.node, country)+ in_stock = is_product_in_stock(root.node, country_code)is_visible = Falseif product_channel_listing:is_visible = product_channel_listing.is_available_for_purchase()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 292b6d7c59..e7b544e196 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2076,10 +2076,6 @@ type GatewayConfigLine {scalar GenericScalar-type Geolocalization {- country: CountryDisplay-}-type GiftCard implements Node {code: Stringuser: User@@ -3657,7 +3653,6 @@ input PaymentInput {gateway: String!token: Stringamount: PositiveDecimal- billingAddress: AddressInputreturnUrl: String}@@ -3853,8 +3848,8 @@ type Product implements Node & ObjectWithMetadata {descriptionJson: JSONString @deprecated(reason: "Will be removed in Saleor 4.0. Use the `description` field instead.")url: String! @deprecated(reason: "This field will be removed after 2020-07-31.")thumbnail(size: Int): Image- pricing: ProductPricingInfo- isAvailable: Boolean+ pricing(address: AddressInput): ProductPricingInfo+ isAvailable(address: AddressInput): BooleantaxType: TaxTypeattributes: [SelectedAttribute!]!channelListings: [ProductChannelListing!]@@ -3906,7 +3901,7 @@ type ProductChannelListing implements Node {purchaseCost: MoneyRangemargin: MarginisAvailableForPurchase: Boolean- pricing: ProductPricingInfo+ pricing(address: AddressInput): ProductPricingInfo}input ProductChannelListingAddInput {@@ -4280,7 +4275,7 @@ type ProductVariant implements Node & ObjectWithMetadata {privateMetadata: [MetadataItem]!metadata: [MetadataItem]!channelListings: [ProductVariantChannelListing!]- pricing: VariantPricingInfo+ pricing(address: AddressInput): VariantPricingInfoattributes(variantSelection: VariantAttributeScope): [SelectedAttribute!]!costPrice: Moneymargin: Int@@ -4289,8 +4284,8 @@ type ProductVariant implements Node & ObjectWithMetadata {images: [ProductImage]translation(languageCode: LanguageCodeEnum!): ProductVariantTranslationdigitalContent: DigitalContent- stocks(countryCode: CountryCode): [Stock]- quantityAvailable(countryCode: CountryCode): Int!+ stocks(address: AddressInput, countryCode: CountryCode): [Stock]+ quantityAvailable(address: AddressInput, countryCode: CountryCode): Int!}type ProductVariantBulkCreate {@@ -4955,7 +4950,6 @@ type Shop {availablePaymentGateways(currency: String): [PaymentGateway!]!availableExternalAuthentications: [ExternalAuthentication!]!availableShippingMethods(channel: String!, address: AddressInput): [ShippingMethod]- geolocalization: Geolocalizationcountries(languageCode: LanguageCodeEnum): [CountryDisplay!]!defaultCountry: CountryDisplaydefaultMailSenderName: Stringdiff --git a/saleor/graphql/shop/tests/benchmark/test_homepage.py b/saleor/graphql/shop/tests/benchmark/test_homepage.pyindex 9931234506..4fc6d489e1 100644--- a/saleor/graphql/shop/tests/benchmark/test_homepage.py+++ b/saleor/graphql/shop/tests/benchmark/test_homepage.py@@ -17,12 +17,6 @@ def test_retrieve_shop(api_client, count_queries):countrycode}- geolocalization {- country {- code- country- }- }}}"""diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex f1f916ce9a..97facbee8a 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -565,30 +565,6 @@ def test_query_default_country(user_api_client, settings):assert data["country"] == "United States of America"-def test_query_geolocalization(user_api_client):- query = """- query {- shop {- geolocalization {- country {- code- }- }- }- }- """- GERMAN_IP = "79.222.222.22"- response = user_api_client.post_graphql(query, HTTP_X_FORWARDED_FOR=GERMAN_IP)- content = get_graphql_content(response)- data = content["data"]["shop"]["geolocalization"]- assert data["country"]["code"] == "DE"-- response = user_api_client.post_graphql(query)- content = get_graphql_content(response)- data = content["data"]["shop"]["geolocalization"]- assert data["country"] is None--AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY = """query{shop {diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex b7f060382c..158cda9b40 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -9,7 +9,6 @@ from phonenumbers import COUNTRY_CODE_TO_REGION_CODEfrom ...account import models as account_modelsfrom ...core.permissions import SitePermissions, get_permissions-from ...core.utils import get_client_ip, get_country_by_ipfrom ...plugins.manager import get_plugins_managerfrom ...site import models as site_modelsfrom ..account.types import Address, AddressInput, StaffNotificationRecipient@@ -50,15 +49,6 @@ class Domain(graphene.ObjectType):description = "Represents shop's domain."-class Geolocalization(graphene.ObjectType):- country = graphene.Field(- CountryDisplay, description="Country of the user acquired by his IP address."- )-- class Meta:- description = "Represents customers's geolocalization data."--class OrderSettings(CountableDjangoObjectType):class Meta:only_fields = ["automatically_confirm_all_new_orders"]@@ -106,9 +96,6 @@ class Shop(graphene.ObjectType):required=False,description="Shipping methods that are available for the shop.",)- geolocalization = graphene.Field(- Geolocalization, description="Customer's geolocalization data."- )countries = graphene.List(graphene.NonNull(CountryDisplay),language_code=graphene.Argument(@@ -221,16 +208,6 @@ class Shop(graphene.ObjectType):url=info.context.build_absolute_uri("/"),)- @staticmethod- def resolve_geolocalization(_, info):- client_ip = get_client_ip(info.context)- country = get_country_by_ip(client_ip)- if country:- return Geolocalization(- country=CountryDisplay(code=country.code, country=country.name)- )- return Geolocalization(country=None)-@staticmethoddef resolve_description(_, info):return info.context.site.settings.descriptiondiff --git a/saleor/graphql/tests/test_utils.py b/saleor/graphql/tests/test_utils.pynew file mode 100644index 0000000000..854d198909--- /dev/null+++ b/saleor/graphql/tests/test_utils.py@@ -0,0 +1,45 @@+import graphene+from django.conf import settings++from ..account.types import AddressInput+from ..utils import get_user_country_context+++def test_get_user_country_context_from_address_instance(address, address_other_country):+ destination_address = address+ company_address = address_other_country++ country = get_user_country_context(destination_address=destination_address)+ assert country == destination_address.country.code++ country = get_user_country_context(company_address=company_address)+ assert country == company_address.country.code++ country = get_user_country_context(+ destination_address=destination_address, company_address=company_address+ )+ assert country == destination_address.country.code++ country = get_user_country_context()+ assert country == settings.DEFAULT_COUNTRY+++def test_get_user_country_from_address_input():+ class Query(graphene.ObjectType):+ field = graphene.Field(graphene.String, address=graphene.Argument(AddressInput))++ @staticmethod+ def resolve_field(_root, _info, address):+ return get_user_country_context(destination_address=address)++ schema = graphene.Schema(query=Query)+ result = schema.execute(+ """+ query {+ field(address: {country: US})+ }+ """+ )++ assert not result.errors+ assert result.data == {"field": "US"}diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 8b5ad8e5c2..acb03edc19 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -1,15 +1,21 @@-from typing import Union+from typing import TYPE_CHECKING, Optional, Unionimport graphene+from django.conf import settingsfrom django.db.models import Valuefrom django.db.models.functions import Concatfrom graphene_django.registry import get_global_registryfrom graphql.error import GraphQLErrorfrom graphql_relay import from_global_id+from ...account import models as account_modelsfrom ..core.enums import PermissionEnumfrom ..core.types import Permission+if TYPE_CHECKING:+ from ..account import types as account_types++ERROR_COULD_NO_RESOLVE_GLOBAL_ID = ("Could not resolve to a node with the global id list of '%s'.")@@ -131,3 +137,26 @@ def get_user_or_app_from_context(context):def requestor_is_superuser(requestor):"""Return True if requestor is superuser."""return getattr(requestor, "is_superuser", False)+++def get_user_country_context(+ destination_address: Optional[+ Union["account_types.AddressInput", "account_models.Address"]+ ] = None,+ company_address: Optional["account_models.Address"] = None,+) -> str:+ """Get country of the current user to use for tax and stock related calculations.++ User's country context is determined from the provided `destination_address` (which+ may represent user's current location determined by the client or a shipping+ address provided in the checkout). If `destination_address` is not given, the+ default company address from the shop settings is assumed. If this address is not+ set, fallback to the `DEFAULT_COUNTRY` setting.+ """+ if destination_address and destination_address.country:+ if isinstance(destination_address, account_models.Address):+ return destination_address.country.code+ return destination_address.country+ elif company_address and company_address.country:+ return company_address.country.code+ return settings.DEFAULT_COUNTRYdiff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 7ad3cf07a8..4fcd9f690e 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -46,7 +46,9 @@ class AvailableQuantityByProductVariantIdAndCountryCodeLoader() -> Iterable[Tuple[int, int]]:results = Stock.objects.filter(product_variant_id__in=variant_ids)if country_code:- results.filter(warehouse__shipping_zones__countries__contains=country_code)+ results = results.filter(+ warehouse__shipping_zones__countries__contains=country_code+ )results = results.annotate_available_quantity()results = results.values_list("product_variant_id", "warehouse__shipping_zones", "available_quantity"@@ -67,7 +69,14 @@ class AvailableQuantityByProductVariantIdAndCountryCodeLoader(variant_id,quantity_by_shipping_zone,) in quantity_by_shipping_zone_by_product_variant.items():- quantity_map[variant_id] = max(quantity_by_shipping_zone.values())+ quantity_values = quantity_by_shipping_zone.values()+ if country_code:+ # When country code is known, return the sum of quantities from all+ # shipping zones supporting given country.+ quantity_map[variant_id] = sum(quantity_values)+ else:+ # When country code is unknown, return the highest known quantity.+ quantity_map[variant_id] = max(quantity_values)# Return the quantities after capping them at the maximum quantity allowed in# checkout. This prevent users from tracking the store's precise stock levels.diff --git a/saleor/graphql/warehouse/tests/test_stock.py b/saleor/graphql/warehouse/tests/test_stock.pyindex dbe769a005..b0102b7fa2 100644--- a/saleor/graphql/warehouse/tests/test_stock.py+++ b/saleor/graphql/warehouse/tests/test_stock.py@@ -1,7 +1,7 @@import graphenefrom ....core.permissions import ProductPermissions-from ....warehouse.models import Stock+from ....warehouse.models import Stock, Warehousefrom ....warehouse.tests.utils import get_quantity_allocated_for_stockfrom ...tests.utils import assert_no_permission, get_graphql_content@@ -163,3 +163,108 @@ def test_query_stocks_with_filters_product_variant__product(total_count== Stock.objects.filter(product_variant__product__name=product.name).count())+++def test_stock_quantities_in_different_warehouses(+ api_client, channel_USD, variant_with_many_stocks_different_shipping_zones+):+ query = """+ query ProductVariant(+ $id: ID!, $channel: String!, $country1: CountryCode, $country2: CountryCode+ ) {+ productVariant(id: $id, channel: $channel) {+ quantityPL: quantityAvailable(address: { country: $country1 })+ quantityUS: quantityAvailable(address: { country: $country2 })+ }+ }+ """++ variant = variant_with_many_stocks_different_shipping_zones+ stock_map = {}+ for stock in variant.stocks.all():+ country = stock.warehouse.shipping_zones.get().countries[0]+ stock_map[country.code] = stock.quantity++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "channel": channel_USD.slug,+ "country1": "PL",+ "country2": "US",+ }+ response = api_client.post_graphql(+ query,+ variables,+ )+ content = get_graphql_content(response)++ assert content["data"]["productVariant"]["quantityPL"] == stock_map["PL"]+ assert content["data"]["productVariant"]["quantityUS"] == stock_map["US"]+++def test_stock_quantity_is_max_from_all_warehouses_without_provided_country(+ api_client, channel_USD, variant_with_many_stocks_different_shipping_zones+):+ query = """+ query ProductVariant($id: ID!, $channel: String!) {+ productVariant(id: $id, channel: $channel) {+ quantityAvailable+ }+ }+ """++ variant = variant_with_many_stocks_different_shipping_zones+ max_warehouse_quantity = max([stock.quantity for stock in variant.stocks.all()])++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "channel": channel_USD.slug,+ }+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ assert (+ content["data"]["productVariant"]["quantityAvailable"] == max_warehouse_quantity+ )+++def test_stock_quantity_is_sum_of_quantities_from_warehouses_that_support_country(+ api_client,+ address,+ channel_USD,+ shipping_zone,+ variant_with_many_stocks_different_shipping_zones,+):+ query = """+ query ProductVariant($id: ID!, $channel: String!, $country: CountryCode) {+ productVariant(id: $id, channel: $channel) {+ quantityAvailable(address: { country: $country })+ }+ }+ """++ variant = variant_with_many_stocks_different_shipping_zones++ # Create another warehouse with a different shipping zone that supports PL. As+ # a result there should be two shipping zones and two warehouses that support PL.+ stocks = variant.stocks.for_country("PL")+ warehouse = Warehouse.objects.create(+ address=address.get_copy(),+ name="WarehousePL",+ slug="warehousePL",+ email="[email protected]",+ )+ warehouse.shipping_zones.add(shipping_zone)+ Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)++ stocks = variant.stocks.for_country("PL")+ sum_quantities = sum([stock.quantity for stock in stocks])++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "channel": channel_USD.slug,+ "country": "PL",+ }+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ assert content["data"]["productVariant"]["quantityAvailable"] == sum_quantitiesdiff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex a26c4cd6f3..97294cb896 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -2,7 +2,6 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Unionimport opentracing-from django.conf import settingsfrom prices import MoneyRange, TaxedMoney, TaxedMoneyRangefrom ...channel.models import Channel@@ -257,9 +256,6 @@ def get_variant_availability(discount = _get_total_discount(undiscounted, discounted)- if country is None:- country = settings.DEFAULT_COUNTRY-if local_currency:price_local_currency = to_local_currency(discounted, local_currency)discount_local_currency = to_local_currency(discount, local_currency)diff --git a/saleor/settings.py b/saleor/settings.pyindex ba16ce5400..931fe4c9f4 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -213,8 +213,6 @@ MIDDLEWARE = ["saleor.core.middleware.request_time","saleor.core.middleware.discounts","saleor.core.middleware.google_analytics",- "saleor.core.middleware.country",- "saleor.core.middleware.currency","saleor.core.middleware.site","saleor.core.middleware.plugins","saleor.core.middleware.jwt_refresh_token_middleware",@@ -355,7 +353,6 @@ AUTH_PASSWORD_VALIDATORS = []DEFAULT_COUNTRY = os.environ.get("DEFAULT_COUNTRY", "US")-DEFAULT_CURRENCY = os.environ.get("DEFAULT_CURRENCY", "USD")DEFAULT_DECIMAL_PLACES = 3DEFAULT_MAX_DIGITS = 12DEFAULT_CURRENCY_CODE_LENGTH = 3diff --git a/saleor/tests/settings.py b/saleor/tests/settings.pyindex ae17de9274..a09a5a1172 100644--- a/saleor/tests/settings.py+++ b/saleor/tests/settings.py@@ -26,8 +26,6 @@ SECRET_KEY = "NOTREALLY"ALLOWED_CLIENT_HOSTS = ["www.example.com"]-DEFAULT_CURRENCY = "USD"-TIME_ZONE = "America/Chicago"LANGUAGE_CODE = "en"diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 1a08d2ddc7..65297247ec 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -53,7 +53,7 @@ def check_stock_quantity_bulk(variants, country_code, quantities):variant_stocks[stock.product_variant_id].append(stock)for variant, quantity in zip(variants, quantities):- stocks = variant_stocks.get(variant.pk)+ stocks = variant_stocks.get(variant.pk, [])available_quantity = sum([stock.available_quantity for stock in stocks])if not stocks:diff --git a/saleor/warehouse/tests/test_stock_availability.py b/saleor/warehouse/tests/test_stock_availability.pyindex fd825c9dc9..ddabbb4c7b 100644--- a/saleor/warehouse/tests/test_stock_availability.py+++ b/saleor/warehouse/tests/test_stock_availability.py@@ -1,7 +1,11 @@import pytestfrom ...core.exceptions import InsufficientStock-from ..availability import check_stock_quantity, get_available_quantity+from ..availability import (+ check_stock_quantity,+ check_stock_quantity_bulk,+ get_available_quantity,+)from ..models import AllocationCOUNTRY_CODE = "US"@@ -66,3 +70,30 @@ def test_get_available_quantity_without_stocks(variant_with_many_stocks):variant_with_many_stocks.stocks.all().delete()available_quantity = get_available_quantity(variant_with_many_stocks, COUNTRY_CODE)assert available_quantity == 0+++def test_check_stock_quantity_bulk(variant_with_many_stocks):+ variant = variant_with_many_stocks+ country_code = "US"+ available_quantity = get_available_quantity(variant, country_code)++ # test that it doesn't raise error for available quantity+ assert (+ check_stock_quantity_bulk(+ [variant_with_many_stocks], country_code, [available_quantity]+ )+ is None+ )++ # test that it raises an error for exceeded quantity+ with pytest.raises(InsufficientStock):+ check_stock_quantity_bulk(+ [variant_with_many_stocks], country_code, [available_quantity + 1]+ )++ # test that it raises an error if no stocks are found+ variant.stocks.all().delete()+ with pytest.raises(InsufficientStock):+ check_stock_quantity_bulk(+ [variant_with_many_stocks], country_code, [available_quantity]+ )