Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve types coverage in Products module (#4998)
Krzysztof Wolskid2273a72c460
diff --git a/poetry.lock b/poetry.lockindex 9e2a5170fe..ee3130210c 100644--- a/poetry.lock+++ b/poetry.lock@@ -733,6 +733,19 @@ google = ["google-cloud-storage (>=1.15.0)"]libcloud = ["apache-libcloud"]sftp = ["paramiko"]+[[package]]+category = "dev"+description = "Mypy stubs for Django"+name = "django-stubs"+optional = false+python-versions = ">=3.6"+version = "1.2.0"++[package.dependencies]+django = "*"+mypy = ">=0.730"+typing-extensions = "*"+[[package]]category = "main"description = "A Django oriented templated / transaction email abstraction"@@ -1359,6 +1372,30 @@ optional = falsepython-versions = ">=3.5"version = "4.6.1"+[[package]]+category = "dev"+description = "Optional static typing for Python"+name = "mypy"+optional = false+python-versions = ">=3.5"+version = "0.740"++[package.dependencies]+mypy-extensions = ">=0.4.0,<0.5.0"+typed-ast = ">=1.4.0,<1.5.0"+typing-extensions = ">=3.7.4"++[package.extras]+dmypy = ["psutil (>=4.0)"]++[[package]]+category = "dev"+description = "Experimental type system extensions for programs checked with the mypy typechecker."+name = "mypy-extensions"+optional = false+python-versions = "*"+version = "0.4.3"+[[package]]category = "dev"description = "Node.js virtual environment builder"@@ -1921,16 +1958,25 @@ description = "Python client for Sentry (https://getsentry.com)"name = "sentry-sdk"optional = falsepython-versions = "*"-version = "0.13.3"+version = "0.13.4"[package.dependencies]certifi = "*"urllib3 = ">=1.10.0"[package.extras]+aiohttp = ["aiohttp (>=3.5)"]+beam = ["beam (>=2.12)"]bottle = ["bottle (>=0.12.13)"]+celery = ["celery (>=3)"]+django = ["django (>=1.8)"]falcon = ["falcon (>=1.4)"]-flask = ["flask (>=0.8)", "blinker (>=1.1)"]+flask = ["flask (>=0.11)", "blinker (>=1.1)"]+pyspark = ["pyspark (>=2.4.4)"]+rq = ["0.6"]+sanic = ["sanic (>=0.8)"]+sqlalchemy = ["sqlalchemy (>=1.2)"]+tornado = ["tornado (>=5)"][[package]]category = "main"@@ -2118,6 +2164,14 @@ version = "0.12.5"six = "*"urllib3 = "*"+[[package]]+category = "dev"+description = "a fork of Python 2 and 3 ast modules with type comment support"+name = "typed-ast"+optional = false+python-versions = "*"+version = "1.4.0"+[[package]]category = "main"description = "Type Hints for Python"@@ -2126,6 +2180,14 @@ optional = falsepython-versions = "*"version = "3.7.4.1"+[[package]]+category = "dev"+description = "Backported and Experimental Type Hints for Python 3.5+"+name = "typing-extensions"+optional = false+python-versions = "*"+version = "3.7.4.1"+[[package]]category = "main"description = "HTTP library with thread-safe connection pooling, file post, and more."@@ -2268,7 +2330,7 @@ docs = ["sphinx", "jaraco.packaging (>=3.2)", "rst.linker (>=1.9)"]testing = ["pathlib2", "contextlib2", "unittest2"][metadata]-content-hash = "324f82ddb69833c88f7ac96782148d4dc2e308686cb230f4e4e54296a0508e8b"+content-hash = "9c4b60cea31ff0d6c702e1ab32cae68c25466057ad48b0ec84ab6172e30c2f12"python-versions = "~3.8"[metadata.files]@@ -2559,6 +2621,10 @@ django-storages = [{file = "django-storages-1.8.tar.gz", hash = "sha256:9322ab74ba6371e2e0fccc350c741686ade829e43085597b26b07ae8955a0a00"},{file = "django_storages-1.8-py2.py3-none-any.whl", hash = "sha256:0a9b7e620e969fb0797523695329ed223bf540bbfdf6cd163b061fc11dab2d1c"},]+django-stubs = [+ {file = "django-stubs-1.2.0.tar.gz", hash = "sha256:c0515576de547bb33057e24d1b0294d10a68e55150ee32fc964f1082192ab012"},+ {file = "django_stubs-1.2.0-py3-none-any.whl", hash = "sha256:ca565958a66c0772a11bf95e415d0bcd476eb59919a7ed1a417cc93315d68809"},+]django-templated-email = [{file = "django-templated-email-2.3.0.tar.gz", hash = "sha256:536c4e5ae099eabfb9aab36087d4d7799948c654e73da55a744213d086d5bb33"},]@@ -2833,6 +2899,26 @@ multidict = [{file = "multidict-4.6.1-cp38-cp38-win_amd64.whl", hash = "sha256:c626029841ada34c030b94a00c573a0c7575fe66489cde148785b6535397d675"},{file = "multidict-4.6.1.tar.gz", hash = "sha256:5159c4975931a1a78bf6602bbebaa366747fce0a56cb2111f44789d2c45e379f"},]+mypy = [+ {file = "mypy-0.740-cp35-cp35m-macosx_10_6_x86_64.whl", hash = "sha256:9371290aa2cad5ad133e4cdc43892778efd13293406f7340b9ffe99d5ec7c1d9"},+ {file = "mypy-0.740-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:b428f883d2b3fe1d052c630642cc6afddd07d5cd7873da948644508be3b9d4a7"},+ {file = "mypy-0.740-cp35-cp35m-win_amd64.whl", hash = "sha256:ace6ac1d0f87d4072f05b5468a084a45b4eda970e4d26704f201e06d47ab2990"},+ {file = "mypy-0.740-cp36-cp36m-macosx_10_6_x86_64.whl", hash = "sha256:d7574e283f83c08501607586b3167728c58e8442947e027d2d4c7dcd6d82f453"},+ {file = "mypy-0.740-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:d5bf0e6ec8ba346a2cf35cb55bf4adfddbc6b6576fcc9e10863daa523e418dbb"},+ {file = "mypy-0.740-cp36-cp36m-win_amd64.whl", hash = "sha256:1521c186a3d200c399bd5573c828ea2db1362af7209b2adb1bb8532cea2fb36f"},+ {file = "mypy-0.740-cp37-cp37m-macosx_10_6_x86_64.whl", hash = "sha256:dc889c84241a857c263a2b1cd1121507db7d5b5f5e87e77147097230f374d10b"},+ {file = "mypy-0.740-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:6ed3b9b3fdc7193ea7aca6f3c20549b377a56f28769783a8f27191903a54170f"},+ {file = "mypy-0.740-cp37-cp37m-win_amd64.whl", hash = "sha256:31a046ab040a84a0fc38bc93694876398e62bc9f35eca8ccbf6418b7297f4c00"},+ {file = "mypy-0.740-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:672e418425d957e276c291930a3921b4a6413204f53fe7c37cad7bc57b9a3391"},+ {file = "mypy-0.740-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:3b1a411909c84b2ae9b8283b58b48541654b918e8513c20a400bb946aa9111ae"},+ {file = "mypy-0.740-cp38-cp38-win_amd64.whl", hash = "sha256:540c9caa57a22d0d5d3c69047cc9dd0094d49782603eb03069821b41f9e970e9"},+ {file = "mypy-0.740-py3-none-any.whl", hash = "sha256:f4748697b349f373002656bf32fede706a0e713d67bfdcf04edf39b1f61d46eb"},+ {file = "mypy-0.740.tar.gz", hash = "sha256:48c8bc99380575deb39f5d3400ebb6a8a1cb5cc669bbba4d3bb30f904e0a0e7d"},+]+mypy-extensions = [+ {file = "mypy_extensions-0.4.3-py2.py3-none-any.whl", hash = "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d"},+ {file = "mypy_extensions-0.4.3.tar.gz", hash = "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8"},+]nodeenv = [{file = "nodeenv-1.3.3.tar.gz", hash = "sha256:ad8259494cf1c9034539f6cced78a1da4840a4b157e23640bc4a0c0546b0cb7a"},]@@ -3129,8 +3215,8 @@ s3transfer = [{file = "s3transfer-0.2.1.tar.gz", hash = "sha256:6efc926738a3cd576c2a79725fed9afde92378aa5c6a957e3af010cb019fac9d"},]sentry-sdk = [- {file = "sentry-sdk-0.13.3.tar.gz", hash = "sha256:e3302e8df82e68599eeeef564f08d15aa62efc1cb013d8e1cccc5bf526d375a4"},- {file = "sentry_sdk-0.13.3-py2.py3-none-any.whl", hash = "sha256:e795f1744066493f9e1eb3d17e0ee19a042a45789b9edd9f553b8b61bc8d399e"},+ {file = "sentry-sdk-0.13.4.tar.gz", hash = "sha256:bfc486af718c268cf49ff43d6334ed4db7333ace420240b630acdd8f8a3a8f60"},+ {file = "sentry_sdk-0.13.4-py2.py3-none-any.whl", hash = "sha256:a7c2c8d3f53b6b57454830cd6a4b73d272f1ba91952f59e6545b3cf885f3c22f"},]singledispatch = [{file = "singledispatch-3.4.0.3-py2.py3-none-any.whl", hash = "sha256:833b46966687b3de7f438c761ac475213e53b306740f1abfaa86e1d1aae56aa8"},@@ -3195,11 +3281,38 @@ transifex-client = [{file = "transifex-client-0.12.5.tar.gz", hash = "sha256:23c88c55d1469b62a771646d4f202b6fe5f4abbcdbe61bda3a3b08c44aaa7a78"},{file = "transifex_client-0.12.5-py2-none-any.whl", hash = "sha256:139867ffaf340aa2b74b0c44fa2d6525bf641357d04b7961a5b10ebe468678d8"},]+typed-ast = [+ {file = "typed_ast-1.4.0-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:262c247a82d005e43b5b7f69aff746370538e176131c32dda9cb0f324d27141e"},+ {file = "typed_ast-1.4.0-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:71211d26ffd12d63a83e079ff258ac9d56a1376a25bc80b1cdcdf601b855b90b"},+ {file = "typed_ast-1.4.0-cp35-cp35m-win32.whl", hash = "sha256:630968c5cdee51a11c05a30453f8cd65e0cc1d2ad0d9192819df9978984529f4"},+ {file = "typed_ast-1.4.0-cp35-cp35m-win_amd64.whl", hash = "sha256:ffde2fbfad571af120fcbfbbc61c72469e72f550d676c3342492a9dfdefb8f12"},+ {file = "typed_ast-1.4.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:4e0b70c6fc4d010f8107726af5fd37921b666f5b31d9331f0bd24ad9a088e631"},+ {file = "typed_ast-1.4.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:bc6c7d3fa1325a0c6613512a093bc2a2a15aeec350451cbdf9e1d4bffe3e3233"},+ {file = "typed_ast-1.4.0-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:cc34a6f5b426748a507dd5d1de4c1978f2eb5626d51326e43280941206c209e1"},+ {file = "typed_ast-1.4.0-cp36-cp36m-win32.whl", hash = "sha256:d896919306dd0aa22d0132f62a1b78d11aaf4c9fc5b3410d3c666b818191630a"},+ {file = "typed_ast-1.4.0-cp36-cp36m-win_amd64.whl", hash = "sha256:354c16e5babd09f5cb0ee000d54cfa38401d8b8891eefa878ac772f827181a3c"},+ {file = "typed_ast-1.4.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:95bd11af7eafc16e829af2d3df510cecfd4387f6453355188342c3e79a2ec87a"},+ {file = "typed_ast-1.4.0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:18511a0b3e7922276346bcb47e2ef9f38fb90fd31cb9223eed42c85d1312344e"},+ {file = "typed_ast-1.4.0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:d7c45933b1bdfaf9f36c579671fec15d25b06c8398f113dab64c18ed1adda01d"},+ {file = "typed_ast-1.4.0-cp37-cp37m-win32.whl", hash = "sha256:d755f03c1e4a51e9b24d899561fec4ccaf51f210d52abdf8c07ee2849b212a36"},+ {file = "typed_ast-1.4.0-cp37-cp37m-win_amd64.whl", hash = "sha256:2b907eb046d049bcd9892e3076c7a6456c93a25bebfe554e931620c90e6a25b0"},+ {file = "typed_ast-1.4.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:fdc1c9bbf79510b76408840e009ed65958feba92a88833cdceecff93ae8fff66"},+ {file = "typed_ast-1.4.0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:7954560051331d003b4e2b3eb822d9dd2e376fa4f6d98fee32f452f52dd6ebb2"},+ {file = "typed_ast-1.4.0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:48e5b1e71f25cfdef98b013263a88d7145879fbb2d5185f2a0c79fa7ebbeae47"},+ {file = "typed_ast-1.4.0-cp38-cp38-win32.whl", hash = "sha256:1170afa46a3799e18b4c977777ce137bb53c7485379d9706af8a59f2ea1aa161"},+ {file = "typed_ast-1.4.0-cp38-cp38-win_amd64.whl", hash = "sha256:838997f4310012cf2e1ad3803bce2f3402e9ffb71ded61b5ee22617b3a7f6b6e"},+ {file = "typed_ast-1.4.0.tar.gz", hash = "sha256:66480f95b8167c9c5c5c87f32cf437d585937970f3fc24386f313a4c97b44e34"},+]typing = [{file = "typing-3.7.4.1-py2-none-any.whl", hash = "sha256:c8cabb5ab8945cd2f54917be357d134db9cc1eb039e59d1606dc1e60cb1d9d36"},{file = "typing-3.7.4.1-py3-none-any.whl", hash = "sha256:f38d83c5a7a7086543a0f649564d661859c5146a85775ab90c0d2f93ffaa9714"},{file = "typing-3.7.4.1.tar.gz", hash = "sha256:91dfe6f3f706ee8cc32d38edbbf304e9b7583fb37108fef38229617f8b3eba23"},]+typing-extensions = [+ {file = "typing_extensions-3.7.4.1-py2-none-any.whl", hash = "sha256:910f4656f54de5993ad9304959ce9bb903f90aadc7c67a0bef07e678014e892d"},+ {file = "typing_extensions-3.7.4.1-py3-none-any.whl", hash = "sha256:cf8b63fedea4d89bab840ecbb93e75578af28f76f66c35889bd7065f5af88575"},+ {file = "typing_extensions-3.7.4.1.tar.gz", hash = "sha256:091ecc894d5e908ac75209f10d5b4f118fbdb2eb1ede6a63544054bb1edb41f2"},+]urllib3 = [{file = "urllib3-1.25.7-py2.py3-none-any.whl", hash = "sha256:a8a318824cc77d1fd4b2bec2ded92646630d7fe8619497b142c84a9e6f5a7293"},{file = "urllib3-1.25.7.tar.gz", hash = "sha256:f3c5fd51747d450d4dcf6f923c81f78f811aab8205fda64b0aba34a4e48b0745"},diff --git a/pyproject.toml b/pyproject.tomlindex 49e81ef9df..6a4477db68 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -98,6 +98,8 @@ pytest-xdist = "^1.29"tox = "^3.13.2"transifex-client = "^0"yapf = "^0.28"+django-stubs = "^1.2"+mypy = "^0.740.0"[tool.black]target_version = ['py35', 'py36', 'py37', 'py38']diff --git a/requirements.txt b/requirements.txtindex 45a2ad2a4f..0506082f38 100644--- a/requirements.txt+++ b/requirements.txt@@ -488,9 +488,9 @@ rx==1.6.1 \s3transfer==0.2.1 \--hash=sha256:b780f2411b824cb541dbcd2c713d0cb61c7d1bcadae204cdddda2b35cef493ba \--hash=sha256:6efc926738a3cd576c2a79725fed9afde92378aa5c6a957e3af010cb019fac9d-sentry-sdk==0.13.3 \- --hash=sha256:e3302e8df82e68599eeeef564f08d15aa62efc1cb013d8e1cccc5bf526d375a4 \- --hash=sha256:e795f1744066493f9e1eb3d17e0ee19a042a45789b9edd9f553b8b61bc8d399e+sentry-sdk==0.13.4 \+ --hash=sha256:bfc486af718c268cf49ff43d6334ed4db7333ace420240b630acdd8f8a3a8f60 \+ --hash=sha256:a7c2c8d3f53b6b57454830cd6a4b73d272f1ba91952f59e6545b3cf885f3c22fsingledispatch==3.4.0.3 \--hash=sha256:833b46966687b3de7f438c761ac475213e53b306740f1abfaa86e1d1aae56aa8 \--hash=sha256:5b06af87df13818d14f08a028e42f566640aef80805c3b50c5056b086e3c2b9cdiff --git a/requirements_dev.txt b/requirements_dev.txtindex 3f6d3ef947..f93263e91d 100644--- a/requirements_dev.txt+++ b/requirements_dev.txt@@ -226,6 +226,9 @@ django-silk==2.0.0 \django-storages==1.8 \--hash=sha256:9322ab74ba6371e2e0fccc350c741686ade829e43085597b26b07ae8955a0a00 \--hash=sha256:0a9b7e620e969fb0797523695329ed223bf540bbfdf6cd163b061fc11dab2d1c+django-stubs==1.2.0 \+ --hash=sha256:c0515576de547bb33057e24d1b0294d10a68e55150ee32fc964f1082192ab012 \+ --hash=sha256:ca565958a66c0772a11bf95e415d0bcd476eb59919a7ed1a417cc93315d68809django-templated-email==2.3.0 \--hash=sha256:536c4e5ae099eabfb9aab36087d4d7799948c654e73da55a744213d086d5bb33django-versatileimagefield==1.11 \@@ -450,6 +453,24 @@ multidict==4.6.1; python_version >= "3.6" \--hash=sha256:87e26d8b89127c25659e962c61a4c655ec7445d19150daea0759516884ecb8b4 \--hash=sha256:c626029841ada34c030b94a00c573a0c7575fe66489cde148785b6535397d675 \--hash=sha256:5159c4975931a1a78bf6602bbebaa366747fce0a56cb2111f44789d2c45e379f+mypy==0.740 \+ --hash=sha256:9371290aa2cad5ad133e4cdc43892778efd13293406f7340b9ffe99d5ec7c1d9 \+ --hash=sha256:b428f883d2b3fe1d052c630642cc6afddd07d5cd7873da948644508be3b9d4a7 \+ --hash=sha256:ace6ac1d0f87d4072f05b5468a084a45b4eda970e4d26704f201e06d47ab2990 \+ --hash=sha256:d7574e283f83c08501607586b3167728c58e8442947e027d2d4c7dcd6d82f453 \+ --hash=sha256:d5bf0e6ec8ba346a2cf35cb55bf4adfddbc6b6576fcc9e10863daa523e418dbb \+ --hash=sha256:1521c186a3d200c399bd5573c828ea2db1362af7209b2adb1bb8532cea2fb36f \+ --hash=sha256:dc889c84241a857c263a2b1cd1121507db7d5b5f5e87e77147097230f374d10b \+ --hash=sha256:6ed3b9b3fdc7193ea7aca6f3c20549b377a56f28769783a8f27191903a54170f \+ --hash=sha256:31a046ab040a84a0fc38bc93694876398e62bc9f35eca8ccbf6418b7297f4c00 \+ --hash=sha256:672e418425d957e276c291930a3921b4a6413204f53fe7c37cad7bc57b9a3391 \+ --hash=sha256:3b1a411909c84b2ae9b8283b58b48541654b918e8513c20a400bb946aa9111ae \+ --hash=sha256:540c9caa57a22d0d5d3c69047cc9dd0094d49782603eb03069821b41f9e970e9 \+ --hash=sha256:f4748697b349f373002656bf32fede706a0e713d67bfdcf04edf39b1f61d46eb \+ --hash=sha256:48c8bc99380575deb39f5d3400ebb6a8a1cb5cc669bbba4d3bb30f904e0a0e7d+mypy-extensions==0.4.3 \+ --hash=sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d \+ --hash=sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8nodeenv==1.3.3 \--hash=sha256:ad8259494cf1c9034539f6cced78a1da4840a4b157e23640bc4a0c0546b0cb7aoauthlib==3.1.0 \@@ -697,9 +718,9 @@ rx==1.6.1 \s3transfer==0.2.1 \--hash=sha256:b780f2411b824cb541dbcd2c713d0cb61c7d1bcadae204cdddda2b35cef493ba \--hash=sha256:6efc926738a3cd576c2a79725fed9afde92378aa5c6a957e3af010cb019fac9d-sentry-sdk==0.13.3 \- --hash=sha256:e3302e8df82e68599eeeef564f08d15aa62efc1cb013d8e1cccc5bf526d375a4 \- --hash=sha256:e795f1744066493f9e1eb3d17e0ee19a042a45789b9edd9f553b8b61bc8d399e+sentry-sdk==0.13.4 \+ --hash=sha256:bfc486af718c268cf49ff43d6334ed4db7333ace420240b630acdd8f8a3a8f60 \+ --hash=sha256:a7c2c8d3f53b6b57454830cd6a4b73d272f1ba91952f59e6545b3cf885f3c22fsingledispatch==3.4.0.3 \--hash=sha256:833b46966687b3de7f438c761ac475213e53b306740f1abfaa86e1d1aae56aa8 \--hash=sha256:5b06af87df13818d14f08a028e42f566640aef80805c3b50c5056b086e3c2b9c@@ -748,10 +769,35 @@ tqdm==4.39.0 \transifex-client==0.12.5 \--hash=sha256:23c88c55d1469b62a771646d4f202b6fe5f4abbcdbe61bda3a3b08c44aaa7a78 \--hash=sha256:139867ffaf340aa2b74b0c44fa2d6525bf641357d04b7961a5b10ebe468678d8+typed-ast==1.4.0 \+ --hash=sha256:262c247a82d005e43b5b7f69aff746370538e176131c32dda9cb0f324d27141e \+ --hash=sha256:71211d26ffd12d63a83e079ff258ac9d56a1376a25bc80b1cdcdf601b855b90b \+ --hash=sha256:630968c5cdee51a11c05a30453f8cd65e0cc1d2ad0d9192819df9978984529f4 \+ --hash=sha256:ffde2fbfad571af120fcbfbbc61c72469e72f550d676c3342492a9dfdefb8f12 \+ --hash=sha256:4e0b70c6fc4d010f8107726af5fd37921b666f5b31d9331f0bd24ad9a088e631 \+ --hash=sha256:bc6c7d3fa1325a0c6613512a093bc2a2a15aeec350451cbdf9e1d4bffe3e3233 \+ --hash=sha256:cc34a6f5b426748a507dd5d1de4c1978f2eb5626d51326e43280941206c209e1 \+ --hash=sha256:d896919306dd0aa22d0132f62a1b78d11aaf4c9fc5b3410d3c666b818191630a \+ --hash=sha256:354c16e5babd09f5cb0ee000d54cfa38401d8b8891eefa878ac772f827181a3c \+ --hash=sha256:95bd11af7eafc16e829af2d3df510cecfd4387f6453355188342c3e79a2ec87a \+ --hash=sha256:18511a0b3e7922276346bcb47e2ef9f38fb90fd31cb9223eed42c85d1312344e \+ --hash=sha256:d7c45933b1bdfaf9f36c579671fec15d25b06c8398f113dab64c18ed1adda01d \+ --hash=sha256:d755f03c1e4a51e9b24d899561fec4ccaf51f210d52abdf8c07ee2849b212a36 \+ --hash=sha256:2b907eb046d049bcd9892e3076c7a6456c93a25bebfe554e931620c90e6a25b0 \+ --hash=sha256:fdc1c9bbf79510b76408840e009ed65958feba92a88833cdceecff93ae8fff66 \+ --hash=sha256:7954560051331d003b4e2b3eb822d9dd2e376fa4f6d98fee32f452f52dd6ebb2 \+ --hash=sha256:48e5b1e71f25cfdef98b013263a88d7145879fbb2d5185f2a0c79fa7ebbeae47 \+ --hash=sha256:1170afa46a3799e18b4c977777ce137bb53c7485379d9706af8a59f2ea1aa161 \+ --hash=sha256:838997f4310012cf2e1ad3803bce2f3402e9ffb71ded61b5ee22617b3a7f6b6e \+ --hash=sha256:66480f95b8167c9c5c5c87f32cf437d585937970f3fc24386f313a4c97b44e34typing==3.7.4.1 \--hash=sha256:c8cabb5ab8945cd2f54917be357d134db9cc1eb039e59d1606dc1e60cb1d9d36 \--hash=sha256:f38d83c5a7a7086543a0f649564d661859c5146a85775ab90c0d2f93ffaa9714 \--hash=sha256:91dfe6f3f706ee8cc32d38edbbf304e9b7583fb37108fef38229617f8b3eba23+typing-extensions==3.7.4.1 \+ --hash=sha256:910f4656f54de5993ad9304959ce9bb903f90aadc7c67a0bef07e678014e892d \+ --hash=sha256:cf8b63fedea4d89bab840ecbb93e75578af28f76f66c35889bd7065f5af88575 \+ --hash=sha256:091ecc894d5e908ac75209f10d5b4f118fbdb2eb1ede6a63544054bb1edb41f2urllib3==1.25.7 \--hash=sha256:a8a318824cc77d1fd4b2bec2ded92646630d7fe8619497b142c84a9e6f5a7293 \--hash=sha256:f3c5fd51747d450d4dcf6f923c81f78f811aab8205fda64b0aba34a4e48b0745diff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 5d980efb44..7d5bca5fd7 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -1,6 +1,6 @@import datetimefrom collections import defaultdict-from typing import TYPE_CHECKING, Dict, Iterable, List, Set+from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Unionfrom django.db.models import Ffrom django.utils import timezone@@ -14,26 +14,25 @@ from .models import NotApplicable, Sale, VoucherCustomerif TYPE_CHECKING:# flake8: noqa- from .types import DiscountsListTypefrom .models import Voucher+ from ..product.models import Productfrom ..checkout.models import Checkout- from ..product.models import Product, Collectionfrom ..order.models import Order-def increase_voucher_usage(voucher: "Voucher"):+def increase_voucher_usage(voucher: "Voucher") -> None:"""Increase voucher uses by 1."""voucher.used = F("used") + 1voucher.save(update_fields=["used"])-def decrease_voucher_usage(voucher: "Voucher"):+def decrease_voucher_usage(voucher: "Voucher") -> None:"""Decrease voucher uses by 1."""voucher.used = F("used") - 1voucher.save(update_fields=["used"])-def add_voucher_usage_by_customer(voucher: "Voucher", customer_email: str):+def add_voucher_usage_by_customer(voucher: "Voucher", customer_email: str) -> None:voucher_customer = VoucherCustomer.objects.filter(voucher=voucher, customer_email=customer_email)@@ -47,7 +46,7 @@ def add_voucher_usage_by_customer(voucher: "Voucher", customer_email: str):VoucherCustomer.objects.create(voucher=voucher, customer_email=customer_email)-def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str):+def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str) -> None:voucher_customer = VoucherCustomer.objects.filter(voucher=voucher, customer_email=customer_email)@@ -56,7 +55,7 @@ def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str):def get_product_discount_on_sale(- product: "Product", product_collections: Set["Collection"], discount: DiscountInfo+ product: "Product", product_collections: Set[str], discount: DiscountInfo):"""Return discount value if product is on sale or raise NotApplicable."""is_product_on_sale = (@@ -71,7 +70,7 @@ def get_product_discount_on_sale()-def get_product_discounts(product: "Product", discounts: "DiscountsListType"):+def get_product_discounts(product: "Product", discounts: "DiscountsListType") -> Money:"""Return discount values for all discounts applicable to a product."""product_collections = set(product.collections.all().values_list("pk", flat=True))for discount in discounts:@@ -110,7 +109,7 @@ def validate_voucher_in_order(order: "Order"):def validate_voucher(voucher: "Voucher", total_price: Money, quantity: int, customer_email: str-):+) -> None:voucher.validate_min_spent(total_price)voucher.validate_min_checkout_items_quantity(quantity)if voucher.apply_once_per_customer:@@ -145,7 +144,7 @@ def _fetch_categories(sale_pks: Iterable[str]) -> Dict[str, Set[str]]:return subcategory_map-def _fetch_collections(sale_pks: Iterable[str]) -> dict:+def _fetch_collections(sale_pks: Iterable[str]) -> Dict[str, set]:collections = Sale.collections.through.objects.filter(sale_id__in=sale_pks).values_list("sale_id", "collection_id")@@ -155,7 +154,7 @@ def _fetch_collections(sale_pks: Iterable[str]) -> dict:return collection_map-def _fetch_products(sale_pks: Iterable[str]) -> dict:+def _fetch_products(sale_pks: Iterable[str]) -> Dict[str, set]:products = Sale.products.through.objects.filter(sale_id__in=sale_pks).values_list("sale_id", "product_id")diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 2fb2b44fd3..5b07a4c61d 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -1,3 +1,4 @@+from dataclasses import asdictfrom typing import List, Unionimport graphene@@ -359,7 +360,7 @@ class ProductVariant(CountableDjangoObjectType, MetadataObjectType):context.currency,extensions=context.extensions,)- return VariantPricingInfo(**availability._asdict())+ return VariantPricingInfo(**asdict(availability))resolve_availability = resolve_pricing@@ -561,7 +562,7 @@ class Product(CountableDjangoObjectType, MetadataObjectType):context.currency,context.extensions,)- return ProductPricingInfo(**availability._asdict())+ return ProductPricingInfo(**asdict(availability))resolve_availability = resolve_pricingdiff --git a/saleor/product/__init__.py b/saleor/product/__init__.pyindex 795ae05a8c..bc87e397b0 100644--- a/saleor/product/__init__.py+++ b/saleor/product/__init__.py@@ -1,7 +1,9 @@+from enum import Enum+from django.utils.translation import pgettext_lazy-class ProductAvailabilityStatus:+class ProductAvailabilityStatus(str, Enum):NOT_PUBLISHED = "not-published"VARIANTS_MISSSING = "variants-missing"OUT_OF_STOCK = "out-of-stock"@@ -27,7 +29,7 @@ class ProductAvailabilityStatus:raise NotImplementedError("Unknown status: %s" % status)-class VariantAvailabilityStatus:+class VariantAvailabilityStatus(str, Enum):AVAILABLE = "available"OUT_OF_STOCK = "out-of-stock"diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 330de57b4c..747b612535 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -1,5 +1,5 @@from decimal import Decimal-from typing import Iterable, Union+from typing import TYPE_CHECKING, Iterable, Unionfrom uuid import uuid4from django.conf import settings@@ -41,6 +41,11 @@ from ..discount.utils import calculate_discounted_pricefrom ..seo.models import SeoModel, SeoModelTranslationfrom . import AttributeInputType+if TYPE_CHECKING:+ from prices import Money++ from ..account.models import User+class Category(MPTTModel, ModelWithMetadata, SeoModel):name = models.CharField(max_length=128)@@ -59,10 +64,10 @@ class Category(MPTTModel, ModelWithMetadata, SeoModel):tree = TreeManager()translated = TranslationProxy()- def __str__(self):+ def __str__(self) -> str:return self.name- def get_absolute_url(self):+ def get_absolute_url(self) -> str:return reverse("product:category", kwargs={"slug": self.slug, "category_id": self.id})@@ -80,10 +85,10 @@ class CategoryTranslation(SeoModelTranslation):class Meta:unique_together = (("language_code", "category"),)- def __str__(self):+ def __str__(self) -> str:return self.name- def __repr__(self):+ def __repr__(self) -> str:class_ = type(self)return "%s(pk=%r, name=%r, category_pk=%r)" % (class_.__name__,@@ -105,10 +110,10 @@ class ProductType(ModelWithMetadata):class Meta:app_label = "product"- def __str__(self):+ def __str__(self) -> str:return self.name- def __repr__(self):+ def __repr__(self) -> str:class_ = type(self)return "<%s.%s(pk=%r, name=%r)>" % (class_.__module__,@@ -148,7 +153,7 @@ class ProductsQueryset(PublishedQuerySet):objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts)- def collection_sorted(self, user):+ def collection_sorted(self, user: "User"):qs = self.visible_to_user(user).prefetch_related("collections__products__collectionproduct")@@ -301,7 +306,7 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):setattr(self, "__variants", self.variants.all())return iter(getattr(self, "__variants"))- def __repr__(self):+ def __repr__(self) -> str:class_ = type(self)return "<%s.%s(pk=%r, name=%r)>" % (class_.__module__,@@ -310,7 +315,7 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):self.name,)- def __str__(self):+ def __str__(self) -> str:return self.namedef save(@@ -323,31 +328,31 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):return super().save(force_insert, force_update, using, update_fields)@property- def plain_text_description(self):+ def plain_text_description(self) -> str:if settings.USE_JSON_CONTENT:return json_content_to_raw_text(self.description_json)return strip_tags(self.description)@property- def is_available(self):+ def is_available(self) -> bool:return self.is_visible and self.is_in_stock()- def get_absolute_url(self):+ def get_absolute_url(self) -> str:return reverse("product:details", kwargs={"slug": self.get_slug(), "product_id": self.id})- def get_slug(self):+ def get_slug(self) -> str:return slugify(smart_text(unidecode(self.name)))- def is_in_stock(self):+ def is_in_stock(self) -> bool:return any(variant.is_in_stock() for variant in self)def get_first_image(self):images = list(self.images.all())return images[0] if images else None- def get_price_range(self, discounts: Iterable[DiscountInfo] = None):+ def get_price_range(self, discounts: Iterable[DiscountInfo] = None) -> MoneyRange:if self.variants.all():prices = [variant.get_price(discounts) for variant in self]return MoneyRange(min(prices), max(prices))@@ -369,10 +374,10 @@ class ProductTranslation(SeoModelTranslation):class Meta:unique_together = (("language_code", "product"),)- def __str__(self):+ def __str__(self) -> str:return self.name- def __repr__(self):+ def __repr__(self) -> str:class_ = type(self)return "%s(pk=%r, name=%r, product_pk=%r)" % (class_.__name__,@@ -462,19 +467,19 @@ class ProductVariant(ModelWithMetadata):class Meta:app_label = "product"- def __str__(self):+ def __str__(self) -> str:return self.name or self.sku@property- def quantity_available(self):+ def quantity_available(self) -> int:return max(self.quantity - self.quantity_allocated, 0)@property- def is_visible(self):+ def is_visible(self) -> bool:return self.product.is_visible@property- def is_available(self):+ def is_available(self) -> bool:return self.is_visible and self.is_in_stock()def check_quantity(self, quantity):@@ -486,37 +491,37 @@ class ProductVariant(ModelWithMetadata):raise InsufficientStock(self)@property- def base_price(self):+ def base_price(self) -> "Money":return (self.price_overrideif self.price_override is not Noneelse self.product.price)- def get_price(self, discounts: Iterable[DiscountInfo] = None):+ def get_price(self, discounts: Iterable[DiscountInfo] = None) -> "Money":return calculate_discounted_price(self.product, self.base_price, discounts)def get_weight(self):return self.weight or self.product.weight or self.product.product_type.weight- def get_absolute_url(self):+ def get_absolute_url(self) -> str:slug = self.product.get_slug()product_id = self.product.idreturn reverse("product:details", kwargs={"slug": slug, "product_id": product_id})- def is_shipping_required(self):+ def is_shipping_required(self) -> bool:return self.product.product_type.is_shipping_required- def is_digital(self):+ def is_digital(self) -> bool:is_digital = self.product.product_type.is_digitalreturn not self.is_shipping_required() and is_digital- def is_in_stock(self):+ def is_in_stock(self) -> bool:return self.quantity_available > 0- def display_product(self, translated=False):+ def display_product(self, translated: bool = False) -> str:if translated:product = self.product.translatedvariant_display = str(self.translated)@@ -528,11 +533,11 @@ class ProductVariant(ModelWithMetadata):)return smart_text(product_display)- def get_first_image(self):+ def get_first_image(self) -> "ProductImage":images = list(self.images.all())return images[0] if images else self.product.get_first_image()- def get_ajax_label(self, discounts=None):+ def get_ajax_label(self, discounts=None) -> str:price = self.get_price(discounts)return "%s, %s, %s" % (self.sku, self.display_product(), prices.amount(price))@@ -610,13 +615,13 @@ class DigitalContentUrl(models.Model):class BaseAttributeQuerySet(models.QuerySet):@staticmethod- def user_has_access_to_all(user):+ def user_has_access_to_all(user: "User") -> bool:return user.is_active and user.has_perm("product.manage_products")def get_public_attributes(self):raise NotImplementedError- def get_visible_to_user(self, user):+ def get_visible_to_user(self, user: "User"):if self.user_has_access_to_all(user):return self.all()return self.get_public_attributes()@@ -797,13 +802,13 @@ class Attribute(ModelWithMetadata):class Meta:ordering = ("storefront_search_position", "slug")- def __str__(self):+ def __str__(self) -> str:return self.name- def get_formfield_name(self):+ def get_formfield_name(self) -> str:return slugify("attribute-%s-%s" % (self.slug, self.pk), allow_unicode=True)- def has_values(self):+ def has_values(self) -> bool:return self.values.exists()@@ -826,7 +831,7 @@ class AttributeTranslation(models.Model):self.attribute_id,)- def __str__(self):+ def __str__(self) -> str:return self.name@@ -844,7 +849,7 @@ class AttributeValue(SortableModel):ordering = ("sort_order", "id")unique_together = ("slug", "attribute")- def __str__(self):+ def __str__(self) -> str:return self.name@property@@ -865,7 +870,7 @@ class AttributeValueTranslation(models.Model):class Meta:unique_together = (("language_code", "attribute_value"),)- def __repr__(self):+ def __repr__(self) -> str:class_ = type(self)return "%s(pk=%r, name=%r, attribute_value_pk=%r)" % (class_.__name__,@@ -874,7 +879,7 @@ class AttributeValueTranslation(models.Model):self.attribute_value_id,)- def __str__(self):+ def __str__(self) -> str:return self.name@@ -940,10 +945,10 @@ class Collection(SeoModel, ModelWithMetadata, PublishableModel):class Meta:ordering = ("slug",)- def __str__(self):+ def __str__(self) -> str:return self.name- def get_absolute_url(self):+ def get_absolute_url(self) -> str:return reverse("product:collection", kwargs={"pk": self.id, "slug": self.slug})@@ -968,5 +973,5 @@ class CollectionTranslation(SeoModelTranslation):self.collection_id,)- def __str__(self):+ def __str__(self) -> str:return self.namediff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex dbe79d82d2..117117a425 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -1,3 +1,5 @@+from typing import Iterable, List, Optional+from ..celeryconf import appfrom ..discount.models import Salefrom .models import Attribute, Product, ProductType, ProductVariant@@ -10,7 +12,7 @@ from .utils.variant_prices import ()-def _update_variants_names(instance, saved_attributes):+def _update_variants_names(instance: ProductVariant, saved_attributes: Iterable):"""Product variant names are created from names of assigned attributes.After change in attribute value name, for all product variants using this@@ -33,21 +35,23 @@ def _update_variants_names(instance, saved_attributes):@app.task-def update_variants_names(product_type_pk, saved_attributes_ids):+def update_variants_names(product_type_pk: List[int], saved_attributes_ids: List[int]):instance = ProductType.objects.get(pk=product_type_pk)saved_attributes = Attribute.objects.filter(pk__in=saved_attributes_ids)- return _update_variants_names(instance, saved_attributes)+ _update_variants_names(instance, saved_attributes)@app.task-def update_product_minimal_variant_price_task(product_pk):+def update_product_minimal_variant_price_task(product_pk: int):product = Product.objects.get(pk=product_pk)update_product_minimal_variant_price(product)@app.taskdef update_products_minimal_variant_prices_of_catalogues_task(- product_ids=None, category_ids=None, collection_ids=None+ product_ids: Optional[List[int]] = None,+ category_ids: Optional[List[int]] = None,+ collection_ids: Optional[List[int]] = None,):update_products_minimal_variant_prices_of_catalogues(product_ids, category_ids, collection_ids@@ -55,13 +59,13 @@ def update_products_minimal_variant_prices_of_catalogues_task(@app.task-def update_products_minimal_variant_prices_of_discount_task(discount_pk):+def update_products_minimal_variant_prices_of_discount_task(discount_pk: int):discount = Sale.objects.get(pk=discount_pk)update_products_minimal_variant_prices_of_discount(discount)@app.task-def update_products_minimal_variant_prices_task(product_ids):+def update_products_minimal_variant_prices_task(product_ids: List[int]):products = Product.objects.filter(pk__in=product_ids)update_products_minimal_variant_prices(products)diff --git a/saleor/product/thumbnails.py b/saleor/product/thumbnails.pyindex 03519ad887..8651eed5d8 100644--- a/saleor/product/thumbnails.py+++ b/saleor/product/thumbnails.py@@ -4,13 +4,13 @@ from .models import Category, Collection, ProductImage@app.task-def create_product_thumbnails(image_id):+def create_product_thumbnails(image_id: str):"""Take a ProductImage model and create thumbnails for it."""create_thumbnails(pk=image_id, model=ProductImage, size_set="products")@app.task-def create_category_background_image_thumbnails(category_id):+def create_category_background_image_thumbnails(category_id: str):"""Take a Product model and create the background image thumbnails for it."""create_thumbnails(pk=category_id,@@ -21,7 +21,7 @@ def create_category_background_image_thumbnails(category_id):@app.task-def create_collection_background_image_thumbnails(collection_id):+def create_collection_background_image_thumbnails(collection_id: str):"""Take a Collection model and create the background image thumbnails for it."""create_thumbnails(pk=collection_id,diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.pyindex 8576db2390..35b94a3a4a 100644--- a/saleor/product/utils/__init__.py+++ b/saleor/product/utils/__init__.py@@ -1,3 +1,4 @@+from typing import TYPE_CHECKING, List, Unionfrom urllib.parse import urlencodefrom django.conf import settings@@ -10,8 +11,19 @@ from ...core.utils.filters import get_now_sorted_byfrom ..tasks import update_products_minimal_variant_prices_taskfrom .availability import products_with_availability+if TYPE_CHECKING:+ # flake8: noqa+ from datetime import date, datetime-def products_visible_to_user(user):+ from django.db.models.query import QuerySet+ from django.http import HttpRequest++ from ...account.models import User+ from ..models import Product, ProductVariant, Collection, ProductImage, Category+ from ..filters import ProductCategoryFilter+++def products_visible_to_user(user: "User") -> "QuerySet[User]":# pylint: disable=cyclic-importfrom ..models import Product@@ -20,7 +32,7 @@ def products_visible_to_user(user):return Product.objects.published()-def products_with_details(user):+def products_with_details(user: "User") -> "QuerySet[Product]":products = products_visible_to_user(user)products = products.prefetch_related("translations",@@ -38,7 +50,7 @@ def products_with_details(user):return products-def products_for_products_list(user):+def products_for_products_list(user: "User") -> "QuerySet[Product]":products = products_visible_to_user(user)products = products.prefetch_related("translations", "images", "variants__variant_images__image"@@ -46,7 +58,9 @@ def products_for_products_list(user):return products-def products_for_homepage(user, homepage_collection):+def products_for_homepage(+ user: "User", homepage_collection: "Collection"+) -> "QuerySet[Product]":products = products_visible_to_user(user)products = products.prefetch_related("translations", "images", "variants__variant_images__image", "collections"@@ -55,22 +69,22 @@ def products_for_homepage(user, homepage_collection):return products-def get_product_images(product):+def get_product_images(product: "Product") -> List["ProductImage"]:"""Return list of product images that will be placed in product gallery."""return list(product.images.all())-def products_for_checkout(user):+def products_for_checkout(user: "User") -> "QuerySet[Product]":products = products_visible_to_user(user)products = products.prefetch_related("variants__variant_images__image")return products-def get_variant_url_from_product(product, attributes):+def get_variant_url_from_product(product: "Product", attributes) -> str:return "%s?%s" % (product.get_absolute_url(), urlencode(attributes))-def get_variant_url(variant):+def get_variant_url(variant: "ProductVariant") -> str:attributes = {str(attribute.pk): attributefor attribute in variant.product.product_type.variant_attributes.all()@@ -78,23 +92,23 @@ def get_variant_url(variant):return get_variant_url_from_product(variant.product, attributes)-def allocate_stock(variant, quantity):+def allocate_stock(variant: "ProductVariant", quantity: int):variant.quantity_allocated = F("quantity_allocated") + quantityvariant.save(update_fields=["quantity_allocated"])-def deallocate_stock(variant, quantity):+def deallocate_stock(variant: "ProductVariant", quantity: int):variant.quantity_allocated = F("quantity_allocated") - quantityvariant.save(update_fields=["quantity_allocated"])-def decrease_stock(variant, quantity):+def decrease_stock(variant: "ProductVariant", quantity: int):variant.quantity = F("quantity") - quantityvariant.quantity_allocated = F("quantity_allocated") - quantityvariant.save(update_fields=["quantity", "quantity_allocated"])-def increase_stock(variant, quantity, allocate=False):+def increase_stock(variant: "ProductVariant", quantity, allocate: bool = False):"""Return given quantity of product to a stock."""variant.quantity = F("quantity") + quantityupdate_fields = ["quantity"]@@ -104,13 +118,10 @@ def increase_stock(variant, quantity, allocate=False):variant.save(update_fields=update_fields)-def get_product_list_context(request, filter_set):- """Build a context from the given filter set.-- :param request: request object- :param filter_set: filter set for product list- :return: context dictionary- """+def get_product_list_context(+ request: "HttpRequest", filter_set: "ProductCategoryFilter"+) -> dict:+ """Build a context from the given filter set."""# Avoiding circular dependencyfrom ..filters import SORT_BY_FIELDS@@ -142,7 +153,7 @@ def get_product_list_context(request, filter_set):}-def collections_visible_to_user(user):+def collections_visible_to_user(user: "User") -> "QuerySet[Collection]":# pylint: disable=cyclic-importfrom ..models import Collection@@ -151,7 +162,9 @@ def collections_visible_to_user(user):return Collection.objects.published()-def calculate_revenue_for_variant(variant, start_date):+def calculate_revenue_for_variant(+ variant: "ProductVariant", start_date: Union["date", "datetime"]+) -> TaxedMoney:"""Calculate total revenue generated by a product variant."""revenue = zero_taxed_money()for order_line in variant.order_lines.all():@@ -162,7 +175,7 @@ def calculate_revenue_for_variant(variant, start_date):return revenue-def collect_categories_tree_products(category):+def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]":"""Collect products from all levels in category tree."""products = category.products.all()descendants = category.get_descendants()@@ -172,7 +185,7 @@ def collect_categories_tree_products(category):@transaction.atomic-def delete_categories(categories_ids):+def delete_categories(categories_ids: List[str]):"""Delete categories and perform all necessary actions.Set products of deleted categories as unpublished, delete categoriesdiff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex 5a8791cbe1..ffa93f0e3a 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -1,8 +1,7 @@-from collections import namedtuple-from decimal import Decimal-from typing import Iterable, Union+from dataclasses import dataclass+from typing import TYPE_CHECKING, Iterable, Optional, Tuple, Union-from prices import TaxedMoneyRange+from prices import TaxedMoney, TaxedMoneyRangefrom saleor.graphql.core.types import MoneyRangefrom saleor.product.models import Product, ProductVariant@@ -12,35 +11,40 @@ from ...discount import DiscountInfofrom ...extensions.manager import get_extensions_managerfrom .. import ProductAvailabilityStatus, VariantAvailabilityStatus-ProductAvailability = namedtuple(- "ProductAvailability",- (- "available",- "on_sale",- "price_range",- "price_range_undiscounted",- "discount",- "price_range_local_currency",- "discount_local_currency",- ),-)--VariantAvailability = namedtuple(- "ProductAvailability",- (- "available",- "on_sale",- "price",- "price_undiscounted",- "discount",- "price_local_currency",- "discount_local_currency",- ),-)+if TYPE_CHECKING:+ from django.db.models.query import QuerySet++ from ...extensions.manager import ExtensionsManager+++@dataclass+class ProductAvailability:+ available: bool+ on_sale: bool+ price_range: TaxedMoneyRange+ price_range_undiscounted: TaxedMoneyRange+ discount: Optional[TaxedMoney]+ price_range_local_currency: Optional[TaxedMoneyRange]+ discount_local_currency: Optional[TaxedMoneyRange]+++@dataclass+class VariantAvailability:+ available: bool+ on_sale: bool+ price: TaxedMoney+ price_undiscounted: TaxedMoney+ discount: Optional[TaxedMoney]+ price_local_currency: Optional[TaxedMoney]+ discount_local_currency: Optional[TaxedMoney]def products_with_availability(- products, discounts, country, local_currency, extensions+ products: "QuerySet[Product]",+ discounts,+ country: str,+ local_currency: str,+ extensions: "ExtensionsManager",):for product in products:yield (@@ -51,7 +55,7 @@ def products_with_availability()-def get_product_availability_status(product):+def get_product_availability_status(product: "Product") -> ProductAvailabilityStatus:is_visible = product.is_visibleare_all_variants_in_stock = all(variant.is_in_stock() for variant in product.variants.all()@@ -75,34 +79,43 @@ def get_product_availability_status(product):return ProductAvailabilityStatus.READY_FOR_PURCHASE-def get_variant_availability_status(variant):+def get_variant_availability_status(+ variant: ProductVariant+) -> VariantAvailabilityStatus:if not variant.is_in_stock():return VariantAvailabilityStatus.OUT_OF_STOCKreturn VariantAvailabilityStatus.AVAILABLE+def _get_total_discount_from_range(+ undiscounted: TaxedMoneyRange, discounted: TaxedMoneyRange+) -> Optional[TaxedMoney]:+ """Calculate the discount amount between two TaxedMoneyRange.++ Subtract two prices and return their total discount, if any.+ Otherwise, it returns None.+ """+ return _get_total_discount(undiscounted.start, discounted.start)++def _get_total_discount(- undiscounted: Union[MoneyRange, TaxedMoneyRange, Decimal],- discounted: Union[MoneyRange, TaxedMoneyRange, Decimal],-):- """Calculate the discount amount between two amounts.+ undiscounted: TaxedMoney, discounted: TaxedMoney+) -> Optional[TaxedMoney]:+ """Calculate the discount amount between two TaxedMoney.- Subtract two prices that are whether a price range or decimal prices- and return their total discount, if any. Otherwise, it returns None.+ Subtract two prices and return their total discount, if any.+ Otherwise, it returns None."""- if not isinstance(undiscounted, (MoneyRange, TaxedMoneyRange)):- if undiscounted > discounted:- return undiscounted - discounted- elif undiscounted.start > discounted.start:- return undiscounted.start - discounted.stop+ if undiscounted > discounted:+ return undiscounted - discountedreturn Nonedef _get_product_price_range(discounted: Union[MoneyRange, TaxedMoneyRange],undiscounted: Union[MoneyRange, TaxedMoneyRange],- local_currency: str = None,-):+ local_currency: Optional[str] = None,+) -> Tuple[TaxedMoneyRange, TaxedMoney]:price_range_local = Nonediscount_local_currency = None@@ -118,9 +131,9 @@ def _get_product_price_range(def get_product_availability(product: Product,discounts: Iterable[DiscountInfo] = None,- country=None,- local_currency=None,- extensions=None,+ country: Optional[str] = None,+ local_currency: Optional[str] = None,+ extensions: Optional["ExtensionsManager"] = None,) -> ProductAvailability:if not extensions:@@ -144,7 +157,7 @@ def get_product_availability(),)- discount = _get_total_discount(undiscounted, discounted)+ discount = _get_total_discount_from_range(undiscounted, discounted)price_range_local, discount_local_currency = _get_product_price_range(discounted, undiscounted, local_currency)@@ -165,9 +178,9 @@ def get_product_availability(def get_variant_availability(variant: ProductVariant,discounts: Iterable[DiscountInfo] = None,- country=None,- local_currency=None,- extensions=None,+ country: Optional[str] = None,+ local_currency: Optional[str] = None,+ extensions: Optional["ExtensionsManager"] = None,) -> VariantAvailability:if not extensions:diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.pyindex c25b6b88d7..0c79d8e177 100644--- a/saleor/product/utils/costs.py+++ b/saleor/product/utils/costs.py@@ -1,9 +1,28 @@+from dataclasses import dataclass+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple+from prices import MoneyRangefrom ...core.taxes import zero_money+if TYPE_CHECKING:+ from prices import Money+ from ..models import Product, ProductVariant+++@dataclass+class CostsData:+ costs: List["Money"]+ margins: List[float]++ def __post_init__(self):+ self.costs = sorted(self.costs)+ self.margins = sorted(self.margins)-def get_product_costs_data(product):++def get_product_costs_data(+ product: "Product"+) -> Tuple[MoneyRange, Tuple[float, float]]:purchase_costs_range = MoneyRange(start=zero_money(), stop=zero_money())margin = (0, 0)@@ -20,15 +39,7 @@ def get_product_costs_data(product):return purchase_costs_range, margin-class CostsData:- __slots__ = ("costs", "margins")-- def __init__(self, costs, margins):- self.costs = sorted(costs)- self.margins = sorted(margins)---def get_cost_data_from_variants(variants):+def get_cost_data_from_variants(variants: Iterable["ProductVariant"]) -> CostsData:costs = []margins = []for variant in variants:@@ -38,7 +49,7 @@ def get_cost_data_from_variants(variants):return CostsData(costs, margins)-def get_variant_costs_data(variant):+def get_variant_costs_data(variant: "ProductVariant") -> CostsData:costs = []margins = []costs.append(get_cost_price(variant))@@ -48,13 +59,13 @@ def get_variant_costs_data(variant):return CostsData(costs, margins)-def get_cost_price(variant):+def get_cost_price(variant: "ProductVariant") -> "Money":if not variant.cost_price:return zero_money()return variant.cost_price-def get_margin_for_variant(variant):+def get_margin_for_variant(variant: "ProductVariant") -> Optional[float]:if variant.cost_price is None:return Nonebase_price = variant.base_pricediff --git a/saleor/product/utils/digital_products.py b/saleor/product/utils/digital_products.pyindex 5647ff2d84..b0216a2fec 100644--- a/saleor/product/utils/digital_products.py+++ b/saleor/product/utils/digital_products.py@@ -7,7 +7,7 @@ from ...account import events as account_eventsfrom ..models import DigitalContentUrl-def get_default_digital_content_settings():+def get_default_digital_content_settings() -> dict:site = Site.objects.get_current()settings = site.settingsreturn {@@ -42,11 +42,11 @@ def digital_content_url_is_valid(content_url: DigitalContentUrl) -> bool:return True-def increment_download_count(self: DigitalContentUrl):- self.download_num += 1- self.save(update_fields=["download_num"])+def increment_download_count(content_url: DigitalContentUrl):+ content_url.download_num += 1+ content_url.save(update_fields=["download_num"])- line = self.line+ line = content_url.lineuser = line.order.user if line else Noneif user is not None:diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.pyindex ecff672717..53ef938427 100644--- a/saleor/product/utils/variants_picker.py+++ b/saleor/product/utils/variants_picker.py@@ -1,6 +1,7 @@from collections import defaultdict+from dataclasses import asdict, dataclass, fieldfrom decimal import Decimal-from typing import Dict, Iterable+from typing import TYPE_CHECKING, Dict, Iterable, List, Optionalfrom django.db.models import Count, Qfrom django_prices.templatetags import prices@@ -10,11 +11,22 @@ from ...core.utils import to_local_currencyfrom ...discount import DiscountInfofrom ...extensions.manager import get_extensions_managerfrom ...seo.schema.product import variant_json_ld-from ..models import AssignedVariantAttribute, ProductVariantfrom .availability import get_product_availability+if TYPE_CHECKING:+ # flake8: noqa+ from prices import MoneyRange, Money-def _attributes_to_map(instance: ProductVariant) -> Dict[str, str]:+ from django.db.models.query import QuerySet++ from ...extensions.manager import ExtensionsManager+ from ..models import AssignedVariantAttribute, ProductVariant, Product+++AttributesMapType = Dict[str, str]+++def _attributes_to_map(instance: "ProductVariant") -> AttributesMapType:"""Convert a variant's attributes to a flat attribute dict ({attr_pk: val_pk}).This is used for backward compatibility between the storefront 1.0@@ -37,29 +49,120 @@ def _attributes_to_map(instance: ProductVariant) -> Dict[str, str]:return attribute_map+@dataclass+class VariantValues:+ pk: str+ name: str+ slug: str+++@dataclass+class VariantAttributes:+ pk: str+ name: str+ slug: str+ values: List[VariantValues]+++@dataclass+class MoneyAsDict:+ currency: str+ gross: Decimal+ grossLocalized: Decimal+ net: Decimal+ netLocalized: Decimal+++@dataclass+class MoneyRangeAsDict:+ minPrice: Optional[MoneyAsDict] = None+ maxPrice: Optional[MoneyAsDict] = None+++@dataclass+class VariantData:+ id: str+ availability: bool+ attributes: AttributesMapType+ schemaData: dict # TODO: Can it be changed to schema?+ price: Optional[MoneyAsDict] = None+ priceUndiscounted: Optional[MoneyAsDict] = None+ priceLocalCurrency: Optional[MoneyAsDict] = None+++@dataclass+class ProductAvailability:+ discount: Optional[MoneyAsDict] = None+ taxRate: Decimal = Decimal(0)+ priceRange: Optional[MoneyRangeAsDict] = None+ priceRangeUndiscounted: Optional[MoneyRangeAsDict] = None+ priceRangeLocalCurrency: Optional[MoneyRangeAsDict] = None+++@dataclass+class ProductPriceDisplay:+ displayGross: bool+ handleTaxes: bool+++@dataclass+class VariantPickerData:+ availability: ProductAvailability+ priceDisplay: ProductPriceDisplay+ variantAttributes: List[VariantAttributes] = field(default_factory=list)+ variants: List[VariantData] = field(default_factory=list)++ def as_dict(self):+ return asdict(self)++def get_variant_picker_data(- product,+ product: "Product",discounts: Iterable[DiscountInfo] = None,- extensions=None,- local_currency=None,- country=None,-):+ extensions: Optional["ExtensionsManager"] = None,+ local_currency: Optional[str] = None,+ country: str = None,+ product_availability: Optional[ProductAvailability] = None,+) -> VariantPickerData:if not extensions:extensions = get_extensions_manager()availability = get_product_availability(product, discounts, country, local_currency, extensions)- variants = product.variants.all()- data = {"variantAttributes": [], "variants": []}++ product_price = extensions.apply_taxes_to_product(product, product.price, country)+ tax_rates = Decimal(0)+ if product_price.tax and product_price.net:+ tax_rates = (product_price.tax / product_price.net) * 100+ tax_rates = tax_rates.quantize(Decimal("1."))++ data = VariantPickerData(+ priceDisplay=ProductPriceDisplay(+ displayGross=display_gross_prices(),+ handleTaxes=extensions.show_taxes_on_storefront(),+ ),+ availability=ProductAvailability(+ discount=price_as_dict(availability.discount),+ taxRate=tax_rates,+ priceRange=price_range_as_dict(availability.price_range),+ priceRangeUndiscounted=price_range_as_dict(+ availability.price_range_undiscounted+ ),+ priceRangeLocalCurrency=price_range_as_dict(+ availability.price_range_local_currency+ ),+ ),+ )variant_attributes = (product.product_type.variant_attributes.all().variant_attributes_sorted())+ variants: "QuerySet[ProductVariant]" = product.variants.all()# Collect only available variantsfilter_available_variants = defaultdict(list)- for variant in variants:+ for variant in variants: # type: ProductVariantprice = extensions.apply_taxes_to_product(variant.product, variant.get_price(discounts), country)@@ -70,19 +173,20 @@ def get_variant_picker_data(price_local_currency = to_local_currency(price, local_currency)else:price_local_currency = None+in_stock = variant.is_in_stock()schema_data = variant_json_ld(price.net, variant, in_stock)attributes_map = _attributes_to_map(variant)- variant_data = {- "id": variant.id,- "availability": in_stock,- "price": price_as_dict(price),- "priceUndiscounted": price_as_dict(price_undiscounted),- "attributes": attributes_map,- "priceLocalCurrency": price_as_dict(price_local_currency),- "schemaData": schema_data,- }- data["variants"].append(variant_data)+ variant_data = VariantData(+ id=variant.pk,+ availability=in_stock,+ price=price_as_dict(price),+ priceUndiscounted=price_as_dict(price_undiscounted),+ attributes=attributes_map,+ priceLocalCurrency=price_as_dict(price_local_currency),+ schemaData=schema_data,+ )+ data.variants.append(variant_data)for variant_key, variant_value in attributes_map.items():filter_available_variants[int(variant_key)].append(variant_value)@@ -91,64 +195,45 @@ def get_variant_picker_data(available_variants = filter_available_variants.get(attribute.pk, None)if available_variants:- data["variantAttributes"].append(- {- "pk": attribute.pk,- "name": attribute.translated.name,- "slug": attribute.translated.slug,- "values": [- {- "pk": value.pk,- "name": value.translated.name,- "slug": value.translated.slug,- }+ data.variantAttributes.append(+ VariantAttributes(+ pk=attribute.pk,+ name=attribute.translated.name,+ slug=attribute.translated.slug,+ values=[+ VariantValues(+ pk=value.pk,+ name=value.translated.name,+ slug=value.translated.slug,+ )for value in attribute.values.filter(pk__in=available_variants).prefetch_related("translations")],- }+ ))- product_price = extensions.apply_taxes_to_product(product, product.price, country)- tax_rates = Decimal(0)- if product_price.tax and product_price.net:- tax_rates = (product_price.tax / product_price.net) * 100- tax_rates = tax_rates.quantize(Decimal("1."))-- data["availability"] = {- "discount": price_as_dict(availability.discount),- "taxRate": tax_rates,- "priceRange": price_range_as_dict(availability.price_range),- "priceRangeUndiscounted": price_range_as_dict(- availability.price_range_undiscounted- ),- "priceRangeLocalCurrency": price_range_as_dict(- availability.price_range_local_currency- ),- }- data["priceDisplay"] = {- "displayGross": display_gross_prices(),- "handleTaxes": extensions.show_taxes_on_storefront(),- }return data-def price_as_dict(price):+def price_as_dict(price: Optional["Money"]) -> Optional[MoneyAsDict]:if price is None:return None- return {- "currency": price.currency,- "gross": price.gross.amount,- "grossLocalized": prices.amount(price.gross),- "net": price.net.amount,- "netLocalized": prices.amount(price.net),- }+ return MoneyAsDict(+ currency=price.currency,+ gross=price.gross.amount,+ grossLocalized=prices.amount(price.gross),+ net=price.net.amount,+ netLocalized=prices.amount(price.net),+ )-def price_range_as_dict(price_range):+def price_range_as_dict(+ price_range: Optional["MoneyRange"]+) -> Optional[MoneyRangeAsDict]:if not price_range:return None- return {- "minPrice": price_as_dict(price_range.start),- "maxPrice": price_as_dict(price_range.stop),- }+ return MoneyRangeAsDict(+ minPrice=price_as_dict(price_range.start),+ maxPrice=price_as_dict(price_range.stop),+ )diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 2ba11a07de..0233ab05ea 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -96,12 +96,13 @@ def product_details(request, slug, product_id, form=None):)product_images = get_product_images(product)variant_picker_data = get_variant_picker_data(- product,- request.discounts,- request.extensions,- request.currency,- request.country,- )+ product=product,+ discounts=request.discounts,+ extensions=request.extensions,+ local_currency=request.currency,+ country=request.country,+ product_availability=availability,+ ).as_dict()# show_variant_picker determines if variant picker is used or select inputshow_variant_picker = all([v["attributes"] for v in variant_picker_data["variants"]]diff --git a/setup.cfg b/setup.cfgindex cd17c782bd..ffbbe6370b 100644--- a/setup.cfg+++ b/setup.cfg@@ -64,3 +64,11 @@ include_trailing_comma: Trueline_length = 88known_first_party = saleorknown_third_party =+++[mypy]+plugins =+ mypy_django_plugin.main++[mypy.plugins.django-stubs]+django_settings_module = saleor.settingsdiff --git a/tests/test_product.py b/tests/test_product.pyindex 7877c44d74..591b5c6762 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -579,7 +579,7 @@ def test_product_filter_sorted_by_wrong_parameter(authorized_client, product, cadef test_get_variant_picker_data_proper_variant_count(product):data = get_variant_picker_data(product, discounts=None, extensions=None, local_currency=None- )+ ).as_dict()assert len(data["variantAttributes"][0]["values"]) == 1@@ -608,7 +608,9 @@ def test_get_variant_picker_data_no_nested_attributes(variant, product_type, cat)product = variant.product- data = get_variant_picker_data(product, discounts=None, local_currency=None)+ data = get_variant_picker_data(+ product, discounts=None, local_currency=None+ ).as_dict()assert len(data["variantAttributes"]) == 0@@ -862,7 +864,7 @@ def test_variant_picker_data_with_translations(product, translated_variant_fr, settings):settings.LANGUAGE_CODE = "fr"- variant_picker_data = get_variant_picker_data(product)+ variant_picker_data = get_variant_picker_data(product).as_dict()attribute = variant_picker_data["variantAttributes"][0]assert attribute["name"] == translated_variant_fr.name@@ -980,7 +982,9 @@ def test_variant_picker_data_price_range(product_type, category):start = TaxedMoney(net=Money("11.00", "USD"), gross=Money("11.00", "USD"))stop = TaxedMoney(net=Money("20.00", "USD"), gross=Money("20.00", "USD"))- picker_data = get_variant_picker_data(product, discounts=None, local_currency=None)+ picker_data = get_variant_picker_data(+ product, discounts=None, local_currency=None+ ).as_dict()min_price = picker_data["availability"]["priceRange"]["minPrice"]min_price = TaxedMoney(diff --git a/tests/test_product_attributes.py b/tests/test_product_attributes.pyindex 2eaaa054c4..d56d21947a 100644--- a/tests/test_product_attributes.py+++ b/tests/test_product_attributes.py@@ -92,6 +92,7 @@ def test_update_variants_changed_does_nothing_with_no_attributes():product_type = MagicMock(spec=ProductType)product_type.variant_attributes.all = Mock(return_value=[])saved_attributes = []+ # FIXME: This method no longer returns any valueassert _update_variants_names(product_type, saved_attributes) is None