Skip to content

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

Introduce static typing for shipping sync webhook responses (#17541)

Iga Karbowiak4163d8e330aa
diff --git a/poetry.lock b/poetry.lock
index 9ab7d912b0..9f658035e6 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -41,6 +41,19 @@ files = [
{file = "aniso8601-7.0.0.tar.gz", hash = "sha256:513d2b6637b7853806ae79ffaca6f3e8754bdd547048f5ccc1420aec4b714f1e"},
]
+[[package]]
+name = "annotated-types"
+version = "0.7.0"
+description = "Reusable constraint types to use with typing.Annotated"
+optional = false
+python-versions = ">=3.8"
+groups = ["main"]
+markers = "platform_python_implementation == \"PyPy\""
+files = [
+ {file = "annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53"},
+ {file = "annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89"},
+]
+
[[package]]
name = "anyio"
version = "4.8.0"
@@ -3917,6 +3930,142 @@ files = [
{file = "pycurl-7.45.4.tar.gz", hash = "sha256:32c8e237069273f4260b6ae13d1e0f99daae938977016021565dc6e11050e803"},
]
+[[package]]
+name = "pydantic"
+version = "2.11.1"
+description = "Data validation using Python type hints"
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+markers = "platform_python_implementation == \"PyPy\""
+files = [
+ {file = "pydantic-2.11.1-py3-none-any.whl", hash = "sha256:5b6c415eee9f8123a14d859be0c84363fec6b1feb6b688d6435801230b56e0b8"},
+ {file = "pydantic-2.11.1.tar.gz", hash = "sha256:442557d2910e75c991c39f4b4ab18963d57b9b55122c8b2a9cd176d8c29ce968"},
+]
+
+[package.dependencies]
+annotated-types = ">=0.6.0"
+pydantic-core = "2.33.0"
+typing-extensions = ">=4.12.2"
+typing-inspection = ">=0.4.0"
+
+[package.extras]
+email = ["email-validator (>=2.0.0)"]
+timezone = ["tzdata ; python_version >= \"3.9\" and platform_system == \"Windows\""]
+
+[[package]]
+name = "pydantic-core"
+version = "2.33.0"
+description = "Core functionality for Pydantic validation and serialization"
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+markers = "platform_python_implementation == \"PyPy\""
+files = [
+ {file = "pydantic_core-2.33.0-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:71dffba8fe9ddff628c68f3abd845e91b028361d43c5f8e7b3f8b91d7d85413e"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:abaeec1be6ed535a5d7ffc2e6c390083c425832b20efd621562fbb5bff6dc518"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:759871f00e26ad3709efc773ac37b4d571de065f9dfb1778012908bcc36b3a73"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:dcfebee69cd5e1c0b76a17e17e347c84b00acebb8dd8edb22d4a03e88e82a207"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1b1262b912435a501fa04cd213720609e2cefa723a07c92017d18693e69bf00b"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4726f1f3f42d6a25678c67da3f0b10f148f5655813c5aca54b0d1742ba821b8f"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e790954b5093dff1e3a9a2523fddc4e79722d6f07993b4cd5547825c3cbf97b5"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:34e7fb3abe375b5c4e64fab75733d605dda0f59827752debc99c17cb2d5f3276"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:ecb158fb9b9091b515213bed3061eb7deb1d3b4e02327c27a0ea714ff46b0760"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-musllinux_1_1_armv7l.whl", hash = "sha256:4d9149e7528af8bbd76cc055967e6e04617dcb2a2afdaa3dea899406c5521faa"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:e81a295adccf73477220e15ff79235ca9dcbcee4be459eb9d4ce9a2763b8386c"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-win32.whl", hash = "sha256:f22dab23cdbce2005f26a8f0c71698457861f97fc6318c75814a50c75e87d025"},
+ {file = "pydantic_core-2.33.0-cp310-cp310-win_amd64.whl", hash = "sha256:9cb2390355ba084c1ad49485d18449b4242da344dea3e0fe10babd1f0db7dcfc"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:a608a75846804271cf9c83e40bbb4dab2ac614d33c6fd5b0c6187f53f5c593ef"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e1c69aa459f5609dec2fa0652d495353accf3eda5bdb18782bc5a2ae45c9273a"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9ec80eb5a5f45a2211793f1c4aeddff0c3761d1c70d684965c1807e923a588b"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e925819a98318d17251776bd3d6aa9f3ff77b965762155bdad15d1a9265c4cfd"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5bf68bb859799e9cec3d9dd8323c40c00a254aabb56fe08f907e437005932f2b"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1b2ea72dea0825949a045fa4071f6d5b3d7620d2a208335207793cf29c5a182d"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1583539533160186ac546b49f5cde9ffc928062c96920f58bd95de32ffd7bffd"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:23c3e77bf8a7317612e5c26a3b084c7edeb9552d645742a54a5867635b4f2453"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a7a7f2a3f628d2f7ef11cb6188bcf0b9e1558151d511b974dfea10a49afe192b"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:f1fb026c575e16f673c61c7b86144517705865173f3d0907040ac30c4f9f5915"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:635702b2fed997e0ac256b2cfbdb4dd0bf7c56b5d8fba8ef03489c03b3eb40e2"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-win32.whl", hash = "sha256:07b4ced28fccae3f00626eaa0c4001aa9ec140a29501770a88dbbb0966019a86"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-win_amd64.whl", hash = "sha256:4927564be53239a87770a5f86bdc272b8d1fbb87ab7783ad70255b4ab01aa25b"},
+ {file = "pydantic_core-2.33.0-cp311-cp311-win_arm64.whl", hash = "sha256:69297418ad644d521ea3e1aa2e14a2a422726167e9ad22b89e8f1130d68e1e9a"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:6c32a40712e3662bebe524abe8abb757f2fa2000028d64cc5a1006016c06af43"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8ec86b5baa36f0a0bfb37db86c7d52652f8e8aa076ab745ef7725784183c3fdd"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4deac83a8cc1d09e40683be0bc6d1fa4cde8df0a9bf0cda5693f9b0569ac01b6"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:175ab598fb457a9aee63206a1993874badf3ed9a456e0654273e56f00747bbd6"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f36afd0d56a6c42cf4e8465b6441cf546ed69d3a4ec92724cc9c8c61bd6ecf4"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0a98257451164666afafc7cbf5fb00d613e33f7e7ebb322fbcd99345695a9a61"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecc6d02d69b54a2eb83ebcc6f29df04957f734bcf309d346b4f83354d8376862"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1a69b7596c6603afd049ce7f3835bcf57dd3892fc7279f0ddf987bebed8caa5a"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:ea30239c148b6ef41364c6f51d103c2988965b643d62e10b233b5efdca8c0099"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:abfa44cf2f7f7d7a199be6c6ec141c9024063205545aa09304349781b9a125e6"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:20d4275f3c4659d92048c70797e5fdc396c6e4446caf517ba5cad2db60cd39d3"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-win32.whl", hash = "sha256:918f2013d7eadea1d88d1a35fd4a1e16aaf90343eb446f91cb091ce7f9b431a2"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-win_amd64.whl", hash = "sha256:aec79acc183865bad120b0190afac467c20b15289050648b876b07777e67ea48"},
+ {file = "pydantic_core-2.33.0-cp312-cp312-win_arm64.whl", hash = "sha256:5461934e895968655225dfa8b3be79e7e927e95d4bd6c2d40edd2fa7052e71b6"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:f00e8b59e1fc8f09d05594aa7d2b726f1b277ca6155fc84c0396db1b373c4555"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:1a73be93ecef45786d7d95b0c5e9b294faf35629d03d5b145b09b81258c7cd6d"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ff48a55be9da6930254565ff5238d71d5e9cd8c5487a191cb85df3bdb8c77365"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:26a4ea04195638dcd8c53dadb545d70badba51735b1594810e9768c2c0b4a5da"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:41d698dcbe12b60661f0632b543dbb119e6ba088103b364ff65e951610cb7ce0"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae62032ef513fe6281ef0009e30838a01057b832dc265da32c10469622613885"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f225f3a3995dbbc26affc191d0443c6c4aa71b83358fd4c2b7d63e2f6f0336f9"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5bdd36b362f419c78d09630cbaebc64913f66f62bda6d42d5fbb08da8cc4f181"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:2a0147c0bef783fd9abc9f016d66edb6cac466dc54a17ec5f5ada08ff65caf5d"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:c860773a0f205926172c6644c394e02c25421dc9a456deff16f64c0e299487d3"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:138d31e3f90087f42aa6286fb640f3c7a8eb7bdae829418265e7e7474bd2574b"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-win32.whl", hash = "sha256:d20cbb9d3e95114325780f3cfe990f3ecae24de7a2d75f978783878cce2ad585"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-win_amd64.whl", hash = "sha256:ca1103d70306489e3d006b0f79db8ca5dd3c977f6f13b2c59ff745249431a606"},
+ {file = "pydantic_core-2.33.0-cp313-cp313-win_arm64.whl", hash = "sha256:6291797cad239285275558e0a27872da735b05c75d5237bbade8736f80e4c225"},
+ {file = "pydantic_core-2.33.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:7b79af799630af263eca9ec87db519426d8c9b3be35016eddad1832bac812d87"},
+ {file = "pydantic_core-2.33.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eabf946a4739b5237f4f56d77fa6668263bc466d06a8036c055587c130a46f7b"},
+ {file = "pydantic_core-2.33.0-cp313-cp313t-win_amd64.whl", hash = "sha256:8a1d581e8cdbb857b0e0e81df98603376c1a5c34dc5e54039dcc00f043df81e7"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-macosx_10_12_x86_64.whl", hash = "sha256:7c9c84749f5787781c1c45bb99f433402e484e515b40675a5d121ea14711cf61"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:64672fa888595a959cfeff957a654e947e65bbe1d7d82f550417cbd6898a1d6b"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:26bc7367c0961dec292244ef2549afa396e72e28cc24706210bd44d947582c59"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ce72d46eb201ca43994303025bd54d8a35a3fc2a3495fac653d6eb7205ce04f4"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:14229c1504287533dbf6b1fc56f752ce2b4e9694022ae7509631ce346158de11"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:085d8985b1c1e48ef271e98a658f562f29d89bda98bf120502283efbc87313eb"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31860fbda80d8f6828e84b4a4d129fd9c4535996b8249cfb8c720dc2a1a00bb8"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f200b2f20856b5a6c3a35f0d4e344019f805e363416e609e9b47c552d35fd5ea"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:5f72914cfd1d0176e58ddc05c7a47674ef4222c8253bf70322923e73e14a4ac3"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-musllinux_1_1_armv7l.whl", hash = "sha256:91301a0980a1d4530d4ba7e6a739ca1a6b31341252cb709948e0aca0860ce0ae"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:7419241e17c7fbe5074ba79143d5523270e04f86f1b3a0dff8df490f84c8273a"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-win32.whl", hash = "sha256:7a25493320203005d2a4dac76d1b7d953cb49bce6d459d9ae38e30dd9f29bc9c"},
+ {file = "pydantic_core-2.33.0-cp39-cp39-win_amd64.whl", hash = "sha256:82a4eba92b7ca8af1b7d5ef5f3d9647eee94d1f74d21ca7c21e3a2b92e008358"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-macosx_10_12_x86_64.whl", hash = "sha256:e2762c568596332fdab56b07060c8ab8362c56cf2a339ee54e491cd503612c50"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:5bf637300ff35d4f59c006fff201c510b2b5e745b07125458a5389af3c0dff8c"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62c151ce3d59ed56ebd7ce9ce5986a409a85db697d25fc232f8e81f195aa39a1"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ee65f0cc652261744fd07f2c6e6901c914aa6c5ff4dcfaf1136bc394d0dd26b"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:024d136ae44d233e6322027bbf356712b3940bee816e6c948ce4b90f18471b3d"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:e37f10f6d4bc67c58fbd727108ae1d8b92b397355e68519f1e4a7babb1473442"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:502ed542e0d958bd12e7c3e9a015bce57deaf50eaa8c2e1c439b512cb9db1e3a"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:715c62af74c236bf386825c0fdfa08d092ab0f191eb5b4580d11c3189af9d330"},
+ {file = "pydantic_core-2.33.0-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:bccc06fa0372151f37f6b69834181aa9eb57cf8665ed36405fb45fbf6cac3bae"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:5d8dc9f63a26f7259b57f46a7aab5af86b2ad6fbe48487500bb1f4b27e051e4c"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:30369e54d6d0113d2aa5aee7a90d17f225c13d87902ace8fcd7bbf99b19124db"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f3eb479354c62067afa62f53bb387827bee2f75c9c79ef25eef6ab84d4b1ae3b"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0310524c833d91403c960b8a3cf9f46c282eadd6afd276c8c5edc617bd705dc9"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:eddb18a00bbb855325db27b4c2a89a4ba491cd6a0bd6d852b225172a1f54b36c"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:ade5dbcf8d9ef8f4b28e682d0b29f3008df9842bb5ac48ac2c17bc55771cc976"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:2c0afd34f928383e3fd25740f2050dbac9d077e7ba5adbaa2227f4d4f3c8da5c"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:7da333f21cd9df51d5731513a6d39319892947604924ddf2e24a4612975fb936"},
+ {file = "pydantic_core-2.33.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:4b6d77c75a57f041c5ee915ff0b0bb58eabb78728b69ed967bc5b780e8f701b8"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-macosx_10_12_x86_64.whl", hash = "sha256:ba95691cf25f63df53c1d342413b41bd7762d9acb425df8858d7efa616c0870e"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:4f1ab031feb8676f6bd7c85abec86e2935850bf19b84432c64e3e239bffeb1ec"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:58c1151827eef98b83d49b6ca6065575876a02d2211f259fb1a6b7757bd24dd8"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a66d931ea2c1464b738ace44b7334ab32a2fd50be023d863935eb00f42be1778"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:0bcf0bab28995d483f6c8d7db25e0d05c3efa5cebfd7f56474359e7137f39856"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:89670d7a0045acb52be0566df5bc8b114ac967c662c06cf5e0c606e4aadc964b"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:b716294e721d8060908dbebe32639b01bfe61b15f9f57bcc18ca9a0e00d9520b"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:fc53e05c16697ff0c1c7c2b98e45e131d4bfb78068fffff92a82d169cbb4c7b7"},
+ {file = "pydantic_core-2.33.0-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:68504959253303d3ae9406b634997a2123a0b0c1da86459abbd0ffc921695eac"},
+ {file = "pydantic_core-2.33.0.tar.gz", hash = "sha256:40eb8af662ba409c3cbf4a8150ad32ae73514cd7cb1f1a2113af39763dd616b3"},
+]
+
+[package.dependencies]
+typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0"
+
[[package]]
name = "pygments"
version = "2.19.1"
@@ -5472,6 +5621,22 @@ files = [
{file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
]
+[[package]]
+name = "typing-inspection"
+version = "0.4.0"
+description = "Runtime typing introspection tools"
+optional = false
+python-versions = ">=3.9"
+groups = ["main"]
+markers = "platform_python_implementation == \"PyPy\""
+files = [
+ {file = "typing_inspection-0.4.0-py3-none-any.whl", hash = "sha256:50e72559fcd2a6367a19f7a7e610e6afcb9fac940c650290eed893d61386832f"},
+ {file = "typing_inspection-0.4.0.tar.gz", hash = "sha256:9765c87de36671694a67904bf2c96e395be9c6439bb6c87b5142569dcdd65122"},
+]
+
+[package.dependencies]
+typing-extensions = ">=4.12.0"
+
[[package]]
name = "tzdata"
version = "2024.2"
@@ -6051,4 +6216,4 @@ type = ["pytest-mypy"]
[metadata]
lock-version = "2.1"
python-versions = "~3.12"
-content-hash = "ed08f72eba1fa28a9002de21546df3bc8b19cc877019bfdb85263caa568cae28"
+content-hash = "eb0d014135f96bc0dcdbfd7c02b90056cc11be2543b004673dd8f1aed334a3d1"
diff --git a/pyproject.toml b/pyproject.toml
index da4b474771..350154ad3a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -124,6 +124,8 @@ package-mode = false
uvicorn = {extras = ["standard"], version = "^0.32.0"}
setuptools = "^76.0.0"
psycopg = {version = "^3.1.8", extras = ["binary"]}
+ pydantic = "^2.10.6"
+ pydantic-core = "^2.33.0"
[tool.poetry.dependencies.celery]
version = ">=4.4.5,<6.0.0"
@@ -206,7 +208,8 @@ warn_redundant_casts = true
warn_unused_ignores = true
plugins = [
- "mypy_django_plugin.main"
+ "mypy_django_plugin.main",
+ "pydantic.mypy"
]
exclude = [
@@ -217,6 +220,10 @@ exclude = [
module = ["saleor.*.migrations.*"]
ignore_errors = true
+[tool.pydantic-mypy]
+init_forbid_extra = true
+init_typed = true
+warn_required_dynamic_aliases = true
[tool.ruff]
target-version = "py312"
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index f76cb8e4d9..9e6446ade8 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -27,6 +27,7 @@ from ..shipping.utils import (
)
from ..warehouse import WarehouseClickAndCollectOption
from ..warehouse.models import Warehouse
+from ..webhook.transport.shipping_helpers import convert_to_app_id_with_identifier
if TYPE_CHECKING:
from ..account.models import Address, User
@@ -219,7 +220,6 @@ class CheckoutInfo:
checkout.save(update_fields=fields_to_update)
def get_delivery_method_info(self) -> "DeliveryMethodBase":
- from ..webhook.transport.shipping import convert_to_app_id_with_identifier
from .utils import get_external_shipping_id
delivery_method: ShippingMethodData | Warehouse | None = None
diff --git a/saleor/core/utils/metadata_manager.py b/saleor/core/utils/metadata_manager.py
index 5eaef55919..6c0a513f21 100644
--- a/saleor/core/utils/metadata_manager.py
+++ b/saleor/core/utils/metadata_manager.py
@@ -1,5 +1,6 @@
from dataclasses import dataclass
from enum import Enum
+from typing import Any
from ...graphql.meta.inputs import MetadataInput
from ..models import ModelWithMetadata
@@ -73,3 +74,12 @@ def create_from_graphql_input(
return MetadataItemCollection(
[MetadataItem(item.key, item.value) for item in items]
)
+
+
+def metadata_is_valid(metadata: Any) -> bool:
+ if not isinstance(metadata, dict):
+ return False
+ for key, value in metadata.items():
+ if not isinstance(key, str) or not isinstance(value, str) or not key.strip():
+ return False
+ return True
diff --git a/saleor/core/utils/tests/test_metadata_manager.py b/saleor/core/utils/tests/test_metadata_manager.py
new file mode 100644
index 0000000000..cb42f77afe
--- /dev/null
+++ b/saleor/core/utils/tests/test_metadata_manager.py
@@ -0,0 +1,38 @@
+import pytest
+
+from ..metadata_manager import metadata_is_valid
+
+
+ "metadata",
+ [
+ {"key1": "value1", "key2": "value2"},
+ {},
+ {"key1": ""},
+ ],
+)
+def test_metadata_is_valid_true(metadata):
+ # when
+ is_metadata_valid = metadata_is_valid(metadata)
+
+ # then
+ assert is_metadata_valid is True
+
+
+ "metadata",
+ [
+ None,
+ "not_a_dict",
+ {"key1": 123},
+ {123: "value1"},
+ {"": "value1"},
+ {" ": "value1"},
+ ],
+)
+def test_metadata_is_valid_false(metadata):
+ # when
+ is_metadata_valid = metadata_is_valid(metadata)
+
+ # then
+ assert is_metadata_valid is False
diff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
index 53af85b858..d02c9f774e 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
@@ -7,7 +7,7 @@ from prices import Money
from .....checkout.utils import assign_external_shipping_to_checkout
from .....shipping.interface import ShippingMethodData
-from .....webhook.transport.shipping import to_shipping_app_id
+from .....webhook.transport.shipping_helpers import to_shipping_app_id
from ....tests.utils import get_graphql_content
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index 96b83c7230..6400a58928 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -17,12 +17,13 @@ from ....webhook.payloads import (
generate_excluded_shipping_methods_for_checkout_payload,
generate_excluded_shipping_methods_for_order_payload,
)
+from ....webhook.response_schemas.shipping import logger as schema_logger
from ....webhook.transport.shipping import (
get_excluded_shipping_methods_from_response,
get_excluded_shipping_methods_or_fetch,
parse_list_shipping_methods_response,
- to_shipping_app_id,
)
+from ....webhook.transport.shipping_helpers import to_shipping_app_id
from ....webhook.transport.synchronous.transport import trigger_webhook_sync
from ....webhook.transport.utils import generate_cache_key_for_webhook
from ...base_plugin import ExcludedShippingMethod
@@ -394,7 +395,8 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or
)
-def test_parse_excluded_shipping_methods_response(app):
[email protected](schema_logger, "warning")
+def test_parse_excluded_shipping_methods_response(mocked_schema_logger, app):
# given
external_id = to_shipping_app_id(app, "test-1234")
response = {
@@ -416,14 +418,21 @@ def test_parse_excluded_shipping_methods_response(app):
},
]
}
+ webhook = Webhook.objects.create(
+ name="shipping-webhook-1",
+ app=app,
+ target_url="https://shipping-gateway.com/apiv2/",
+ )
# when
- excluded_methods = get_excluded_shipping_methods_from_response(response)
+ excluded_methods = get_excluded_shipping_methods_from_response(response, webhook)
# then
assert len(excluded_methods) == 2
- assert excluded_methods[0]["id"] == "2"
- assert excluded_methods[1]["id"] == external_id
+ assert excluded_methods[0].id == "2"
+ assert excluded_methods[1].id == external_id
+ # 2 warning for each invalid data
+ assert mocked_schema_logger.call_count == 6
@mock.patch(
@@ -1243,7 +1252,10 @@ def test_get_excluded_shipping_methods_or_fetch_invalid_response_type(
mocked_parse.assert_called_once_with([])
-def test_parse_list_shipping_methods_response_response_incorrect_format(app):
[email protected](schema_logger, "warning")
+def test_parse_list_shipping_methods_response_response_incorrect_format(
+ mocked_logger, app
+):
# given
response_data_with_incorrect_format = [[1], 2, "3"]
# when
@@ -1252,6 +1264,8 @@ def test_parse_list_shipping_methods_response_response_incorrect_format(app):
)
# then
assert result == []
+ # Ensure the warning about invalit method data wa logged
+ assert mocked_logger.call_count == len(response_data_with_incorrect_format)
def test_parse_list_shipping_methods_with_metadata(app):
@@ -1310,6 +1324,7 @@ def test_parse_list_shipping_methods_metadata_absent_in_response(app):
]
# when
response = parse_list_shipping_methods_response(response_data_with_meta, app)
+
# then
assert response[0].metadata == {}
@@ -1318,7 +1333,7 @@ def test_parse_list_shipping_methods_metadata_is_none(app):
# given
response_data_with_meta = [
{
- "id": 123,
+ "id": "123",
"amount": 10,
"currency": "USD",
"name": "shipping",
diff --git a/saleor/webhook/response_schemas/__init__.py b/saleor/webhook/response_schemas/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/response_schemas/annotations.py b/saleor/webhook/response_schemas/annotations.py
new file mode 100644
index 0000000000..9f39a437ca
--- /dev/null
+++ b/saleor/webhook/response_schemas/annotations.py
@@ -0,0 +1,27 @@
+from typing import Annotated, Any, TypeVar
+
+from pydantic import (
+ BeforeValidator,
+)
+from pydantic_core import PydanticUseDefault
+
+from ...core.utils.metadata_manager import metadata_is_valid
+
+
+def skip_invalid_metadata(value: Any) -> Any:
+ if not metadata_is_valid(value):
+ raise PydanticUseDefault()
+ return value
+
+
+Metadata = Annotated[dict[str, str], BeforeValidator(skip_invalid_metadata)]
+
+
+def default_if_none(value: Any) -> Any:
+ if value is None:
+ raise PydanticUseDefault()
+ return value
+
+
+T = TypeVar("T")
+DefaultIfNone = Annotated[T, BeforeValidator(default_if_none)]
diff --git a/saleor/webhook/response_schemas/shipping.py b/saleor/webhook/response_schemas/shipping.py
new file mode 100644
index 0000000000..0c5ec2b653
--- /dev/null
+++ b/saleor/webhook/response_schemas/shipping.py
@@ -0,0 +1,86 @@
+import logging
+from decimal import Decimal
+from typing import Annotated, Any, TypeVar
+
+from graphql.error import GraphQLError
+from prices import Money
+from pydantic import (
+ BaseModel,
+ Field,
+ RootModel,
+ ValidationError,
+ ValidatorFunctionWrapHandler,
+ WrapValidator,
+ field_validator,
+)
+from pydantic_core import PydanticOmit
+
+from ...graphql.core.utils import from_global_id_or_error
+from ...shipping.models import ShippingMethod
+from ..const import APP_ID_PREFIX
+from .annotations import DefaultIfNone, Metadata
+
+logger = logging.getLogger(__name__)
+
+name_max_length = ShippingMethod._meta.get_field("name").max_length
+
+T = TypeVar("T")
+
+
+def skip_invalid_shipping_method(
+ value: Any, handler: ValidatorFunctionWrapHandler
+) -> Any:
+ try:
+ return handler(value)
+ except ValidationError as err:
+ logger.warning("Skipping invalid shipping method: %s", err)
+ raise PydanticOmit() from err
+
+
+OnErrorSkipShippingMethod = Annotated[T, WrapValidator(skip_invalid_shipping_method)]
+
+
+class ShippingMethodSchema(BaseModel):
+ id: str = Field(coerce_numbers_to_str=True)
+ name: str = Field(max_length=name_max_length)
+ amount: Decimal = Field(ge=0)
+ currency: str
+ maximum_delivery_days: Annotated[int, Field(ge=0)] | None = None
+ minimum_delivery_days: Annotated[int, Field(ge=0)] | None = None
+ description: str | None = None
+ metadata: DefaultIfNone[Metadata] = {}
+
+ @property
+ def price(self) -> Money:
+ return Money(self.amount, self.currency)
+
+
+class ListShippingMethodsSchema(RootModel):
+ root: DefaultIfNone[list[OnErrorSkipShippingMethod[ShippingMethodSchema]]] = []
+
+
+class ExcludedShippingMethodSchema(BaseModel):
+ id: str
+ reason: DefaultIfNone[str] = ""
+
+ @field_validator("id", mode="after")
+ @classmethod
+ def clean_id(cls, value: str) -> str:
+ try:
+ type_name, method_id = from_global_id_or_error(value)
+ except (KeyError, ValueError, TypeError, GraphQLError) as e:
+ error_msg = "Malformed ShippingMethod id was provided: %s"
+ logger.warning(error_msg, value)
+ raise ValueError(error_msg, e) from e
+
+ if type_name not in (APP_ID_PREFIX, "ShippingMethod"):
+ error_msg = "Invalid type received. Expected ShippingMethod, got %s"
+ logger.warning(error_msg, type_name)
+ raise ValueError(error_msg, type_name)
+ return method_id
+
+
+class FilterShippingMethodsSchema(BaseModel):
+ excluded_methods: DefaultIfNone[
+ list[OnErrorSkipShippingMethod[ExcludedShippingMethodSchema]]
+ ] = []
diff --git a/saleor/webhook/tests/response_schemas/__init__.py b/saleor/webhook/tests/response_schemas/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/webhook/tests/response_schemas/test_shipping.py b/saleor/webhook/tests/response_schemas/test_shipping.py
new file mode 100644
index 0000000000..c590d0b453
--- /dev/null
+++ b/saleor/webhook/tests/response_schemas/test_shipping.py
@@ -0,0 +1,352 @@
+import base64
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+import pytest
+from pydantic import ValidationError
+
+from ...response_schemas.shipping import (
+ ExcludedShippingMethodSchema,
+ FilterShippingMethodsSchema,
+ ListShippingMethodsSchema,
+ ShippingMethodSchema,
+ logger,
+)
+
+
+def decode_id(id):
+ return base64.b64decode(id).decode()
+
+
+ "data",
+ [
+ # All fields provided
+ {
+ "id": "1",
+ "name": "Standard Shipping",
+ "amount": Decimal("10.00"),
+ "currency": "USD",
+ "maximum_delivery_days": 5,
+ "minimum_delivery_days": 2,
+ "description": "Fast delivery",
+ "metadata": {"key1": "value1", "key2": "value2"},
+ },
+ # Optional fields not provided
+ {
+ "id": 2, # Integer ID
+ "name": "Express Shipping",
+ "amount": Decimal("20.00"),
+ "currency": "EUR",
+ },
+ # Metadata is empty, delivery days, and description as None
+ {
+ "id": "3",
+ "name": "Overnight Shipping",
+ "amount": Decimal("50.00"),
+ "currency": "GBP",
+ "maximum_delivery_days": None,
+ "minimum_delivery_days": None,
+ "description": None,
+ "metadata": {}, # Empty metadata
+ },
+ # No description or metadata
+ {
+ "id": "4",
+ "name": "Free Shipping",
+ "amount": Decimal("0.00"),
+ "currency": "USD",
+ "maximum_delivery_days": 7,
+ "minimum_delivery_days": 5,
+ },
+ # Metadata is None
+ {
+ "id": 5,
+ "name": "International Shipping",
+ "amount": Decimal("30.00"),
+ "currency": "USD",
+ "description": None,
+ "metadata": None,
+ },
+ ],
+)
+def test_shipping_method_schema_valid(data):
+ # when
+ shipping_method_model = ShippingMethodSchema.model_validate(data)
+
+ # then
+ assert shipping_method_model.id == str(data["id"])
+ assert shipping_method_model.name == data["name"]
+ assert shipping_method_model.amount == data["amount"]
+ assert shipping_method_model.currency == data["currency"]
+ assert shipping_method_model.maximum_delivery_days == data.get(
+ "maximum_delivery_days"
+ )
+ assert shipping_method_model.minimum_delivery_days == data.get(
+ "minimum_delivery_days"
+ )
+ assert shipping_method_model.description == data.get("description")
+ assert shipping_method_model.metadata == (data.get("metadata") or {})
+
+
+ "metadata", [12345, "not_a_dict", {123: 123}, {"123": 123}, {123: "123"}]
+)
+def test_shipping_method_schema_invalid_metadata_skipped(metadata):
+ # given
+ data = {
+ "id": "4",
+ "name": "Free Shipping",
+ "amount": Decimal("0.00"),
+ "currency": "USD",
+ "metadata": metadata,
+ }
+
+ # when
+ shipping_method_model = ShippingMethodSchema.model_validate(data)
+
+ # then
+ assert shipping_method_model.id == data["id"]
+ assert shipping_method_model.name == data["name"]
+ assert shipping_method_model.amount == data["amount"]
+ assert shipping_method_model.currency == data["currency"]
+ assert shipping_method_model.maximum_delivery_days is None
+ assert shipping_method_model.minimum_delivery_days is None
+ assert shipping_method_model.description is None
+ assert shipping_method_model.metadata == {}
+
+
+ "data",
+ [
+ # Missing required fields - missing id
+ {
+ "name": "Standard Shipping",
+ "amount": Decimal("10.00"),
+ "currency": "USD",
+ },
+ # Missing required fields - missing name
+ {
+ "id": 0,
+ "amount": Decimal("10.00"),
+ "currency": "USD",
+ },
+ # Missing required fields - missing amount
+ {
+ "id": 0,
+ "name": "Standard Shipping",
+ "currency": "USD",
+ },
+ # Invalid type for "id"
+ {
+ "id": {"invalid": "dict"},
+ "name": "Standard Shipping",
+ "amount": Decimal("10.00"),
+ "currency": "USD",
+ },
+ # Invalid type for "amount"
+ {
+ "id": "1",
+ "name": "Standard Shipping",
+ "amount": "invalid_amount",
+ "currency": "USD",
+ },
+ # Negative value for "amount"
+ {
+ "id": "2",
+ "name": "Express Shipping",
+ "amount": Decimal("-10.00"),
+ "currency": "USD",
+ },
+ # Invalid type for "maximum_delivery_days"
+ {
+ "id": "5",
+ "name": "International Shipping",
+ "amount": Decimal("30.00"),
+ "currency": "USD",
+ "maximum_delivery_days": "invalid_days",
+ },
+ # Invalid type for "minimum_delivery_days"
+ {
+ "id": "5",
+ "name": "International Shipping",
+ "amount": Decimal("30.00"),
+ "currency": "USD",
+ "minimum_delivery_days": "invalid_days",
+ },
+ # Negative value for "maximum_delivery_days"
+ {
+ "id": 6,
+ "name": "Economy Shipping",
+ "amount": Decimal("5.00"),
+ "currency": "USD",
+ "maximum_delivery_days": -1,
+ },
+ # Negative value for "minimum_delivery_days"
+ {
+ "id": 6,
+ "name": "Economy Shipping",
+ "amount": Decimal("5.00"),
+ "currency": "USD",
+ "minimum_delivery_days": -1,
+ },
+ # Name exceeds max length
+ {
+ "id": 7,
+ "name": "A" * 300,
+ "amount": Decimal("15.00"),
+ "currency": "USD",
+ },
+ ],
+)
+def test_shipping_method_schema_invalid(data):
+ with pytest.raises(ValidationError):
+ ShippingMethodSchema.model_validate(data)
+
+
[email protected]("data", [None, []])
+def test_list_shipping_methods_schema_skipped_values(data):
+ # when
+ list_methods = ListShippingMethodsSchema.model_validate(data)
+
+ # Then the root should be an empty list
+ assert list_methods.root == []
+
+
[email protected](logger, "warning")
+def test_list_shipping_methods_schema_invalid_element_skipped(mocked_logger):
+ """Test when the provided input has 2 elements, one valid and one invalid."""
+ # given a list with one valid and one invalid shipping method
+ data = [
+ {
+ "id": "1",
+ "name": "Standard Shipping",
+ "amount": Decimal("10.00"),
+ "currency": "USD",
+ "maximum_delivery_days": 5,
+ "minimum_delivery_days": 2,
+ "description": "Fast delivery",
+ "metadata": {"key1": "value1", "key2": "value2"},
+ },
+ {
+ "id": "2",
+ "name": "Express Shipping",
+ "amount": "invalid_amount", # Invalid amount
+ "currency": "EUR",
+ },
+ ]
+
+ # when
+ schema = ListShippingMethodsSchema.model_validate(data)
+
+ # then only the valid shipping method should be included
+ assert len(schema.root) == 1
+ assert schema.root[0].id == data[0]["id"]
+ assert schema.root[0].name == data[0]["name"]
+ assert mocked_logger.call_count == 1
+
+
+ "data",
+ [
+ {"id": graphene.Node.to_global_id("app", "123"), "reason": "Some reason"},
+ {"id": graphene.Node.to_global_id("app", "456"), "reason": None},
+ {"id": graphene.Node.to_global_id("app", "789"), "reason": ""},
+ ],
+)
+def test_excluded_shipping_method_schema_valid_external_method(data):
+ # when
+ excluded_method_data = ExcludedShippingMethodSchema.model_validate(data)
+
+ # then
+ assert excluded_method_data.id == data["id"]
+ assert excluded_method_data.reason == (data["reason"] or "")
+
+
+ "data",
+ [
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "123"),
+ "reason": "Some reason",
+ },
+ {"id": graphene.Node.to_global_id("ShippingMethod", "456"), "reason": None},
+ {"id": graphene.Node.to_global_id("ShippingMethod", "789"), "reason": ""},
+ ],
+)
+def test_excluded_shipping_method_schema_valid_shipping_method(data):
+ # when
+ excluded_method_data = ExcludedShippingMethodSchema.model_validate(data)
+
+ # then
+ assert excluded_method_data.id == graphene.Node.from_global_id(data["id"])[1]
+ assert excluded_method_data.reason == (data["reason"] or "")
+
+
+ "id",
+ [
+ "invalid_id",
+ "123",
+ graphene.Node.to_global_id("ABC", "123"),
+ ],
+)
[email protected](logger, "warning")
+def test_excluded_shipping_method_schema_invalid_id(mocked_logger, id):
+ # given
+ data = {"id": id, "reason": "Some reason"}
+
+ # when
+ with pytest.raises(ValidationError):
+ ExcludedShippingMethodSchema.model_validate(data)
+
+ # then
+ assert mocked_logger.call_count == 1
+
+
[email protected]("data", [None, []])
+def test_filter_shipping_methods_schema_skipped_values(data):
+ # given
+ input_data = {"excluded_methods": data}
+
+ # when
+ list_methods = FilterShippingMethodsSchema.model_validate(input_data)
+
+ # Then the root should be an empty list
+ assert list_methods.excluded_methods == []
+
+
[email protected](logger, "warning")
+def test_filter_shipping_methods_schema_invalid_element_skipped(mocked_logger):
+ """Test when the provided input has 2 elements, one valid and one invalid."""
+ # given a list with one valid and one invalid shipping method
+ data = {
+ "excluded_methods": [
+ {
+ "id": graphene.Node.to_global_id("app", "123"),
+ "reason": "Some reason",
+ },
+ {
+ "id": "INVALID",
+ "reason": None,
+ },
+ {
+ "id": graphene.Node.to_global_id("ShippingMethod", "456"),
+ "reason": None,
+ },
+ ]
+ }
+
+ # when
+ schema = FilterShippingMethodsSchema.model_validate(data)
+
+ # then only the valid shipping method should be included
+ assert len(schema.excluded_methods) == 2
+ assert schema.excluded_methods[0].id == data["excluded_methods"][0]["id"]
+ assert schema.excluded_methods[0].reason == data["excluded_methods"][0]["reason"]
+ assert (
+ schema.excluded_methods[1].id
+ == graphene.Node.from_global_id(data["excluded_methods"][2]["id"])[1]
+ )
+ assert schema.excluded_methods[1].reason == ""
diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.py
index 447d95ee88..dd5aa03230 100644
--- a/saleor/webhook/transport/shipping.py
+++ b/saleor/webhook/transport/shipping.py
@@ -1,4 +1,3 @@
-import base64
import json
import logging
from collections import defaultdict
@@ -6,101 +5,51 @@ from collections.abc import Callable
from typing import Any, Union
from django.db.models import QuerySet
-from graphql import GraphQLError
-from prices import Money
+from pydantic import ValidationError
from ...app.models import App
from ...checkout.models import Checkout
-from ...graphql.core.utils import from_global_id_or_error
-from ...graphql.shipping.types import ShippingMethod
from ...graphql.webhook.utils import get_pregenerated_subscription_payload
from ...order.models import Order
from ...plugins.base_plugin import ExcludedShippingMethod, RequestorOrLazyObject
from ...settings import WEBHOOK_SYNC_TIMEOUT
from ...shipping.interface import ShippingMethodData
from ...webhook.utils import get_webhooks_for_event
-from ..const import APP_ID_PREFIX, CACHE_EXCLUDED_SHIPPING_TIME
+from ..const import CACHE_EXCLUDED_SHIPPING_TIME
+from ..models import Webhook
+from ..response_schemas.shipping import (
+ ExcludedShippingMethodSchema,
+ FilterShippingMethodsSchema,
+ ListShippingMethodsSchema,
+)
+from .shipping_helpers import to_shipping_app_id
from .synchronous.transport import trigger_webhook_sync_if_not_cached
logger = logging.getLogger(__name__)
-def to_shipping_app_id(app: App, shipping_method_id: str) -> str:
- app_identifier = app.identifier or app.id
- return base64.b64encode(
- str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}")
- ).decode("utf-8")
-
-
-def convert_to_app_id_with_identifier(shipping_app_id: str) -> None | str:
- """Prepare the shipping_app_id in format `app:<app-identifier>/method_id>`.
-
- The format of shipping_app_id has been changes so we need to support both of them.
- This method is preparing the new shipping_app_id format based on assumptions
- that right now the old one is used which is `app:<app-pk>:method_id>`
- """
- decoded_id = base64.b64decode(shipping_app_id).decode()
- splitted_id = decoded_id.split(":")
- if len(splitted_id) != 3:
- return None
- try:
- app_id = int(splitted_id[1])
- except (TypeError, ValueError):
- return None
- app = App.objects.filter(id=app_id).first()
- if app is None:
- return None
- return to_shipping_app_id(app, splitted_id[2])
-
-
-def method_metadata_is_valid(metadata) -> bool:
- if not isinstance(metadata, dict):
- return False
- for key, value in metadata.items():
- if not isinstance(key, str) or not isinstance(value, str) or not key.strip():
- return False
- return True
-
-
def parse_list_shipping_methods_response(
response_data: Any, app: "App"
) -> list["ShippingMethodData"]:
- shipping_methods = []
- for shipping_method_data in response_data:
- if not validate_shipping_method_data(shipping_method_data):
- continue
- method_id = shipping_method_data.get("id")
- method_name = shipping_method_data.get("name")
- method_amount = shipping_method_data.get("amount")
- method_currency = shipping_method_data.get("currency")
- method_maximum_delivery_days = shipping_method_data.get("maximum_delivery_days")
- method_minimum_delivery_days = shipping_method_data.get("minimum_delivery_days")
- method_description = shipping_method_data.get("description")
- method_metadata = shipping_method_data.get("metadata") or {}
- if method_metadata:
- method_metadata = (
- method_metadata if method_metadata_is_valid(method_metadata) else {}
- )
-
- shipping_methods.append(
- ShippingMethodData(
- id=to_shipping_app_id(app, method_id),
- name=method_name,
- price=Money(method_amount, method_currency),
- maximum_delivery_days=method_maximum_delivery_days,
- minimum_delivery_days=method_minimum_delivery_days,
- description=method_description,
- metadata=method_metadata,
- )
+ try:
+ list_shipping_method_model = ListShippingMethodsSchema.model_validate(
+ response_data
)
- return shipping_methods
-
-
-def validate_shipping_method_data(shipping_method_data):
- if not isinstance(shipping_method_data, dict):
- return False
- keys = ["id", "name", "amount", "currency"]
- return all(key in shipping_method_data for key in keys)
+ except ValidationError:
+ logger.warning("Skipping invalid shipping method response: %s", response_data)
+ return []
+ return [
+ ShippingMethodData(
+ id=to_shipping_app_id(app, str(shipping_method.id)),
+ name=shipping_method.name,
+ price=shipping_method.price,
+ maximum_delivery_days=shipping_method.maximum_delivery_days,
+ minimum_delivery_days=shipping_method.minimum_delivery_days,
+ description=shipping_method.description,
+ metadata=shipping_method.metadata,
+ )
+ for shipping_method in list_shipping_method_model.root
+ ]
def get_cache_data_for_exclude_shipping_methods(payload: str) -> dict:
@@ -131,7 +80,7 @@ def get_excluded_shipping_methods_or_fetch(
if pregenerated_subscription_payloads is None:
pregenerated_subscription_payloads = {}
cache_data = get_cache_data_for_exclude_shipping_methods(payload)
- excluded_methods = []
+ excluded_methods: list[ExcludedShippingMethodSchema] = []
# Gather responses from webhooks
for webhook in webhooks:
pregenerated_subscription_payload = get_pregenerated_subscription_payload(
@@ -151,7 +100,7 @@ def get_excluded_shipping_methods_or_fetch(
)
if response_data and isinstance(response_data, dict):
excluded_methods.extend(
- get_excluded_shipping_methods_from_response(response_data)
+ get_excluded_shipping_methods_from_response(response_data, webhook)
)
return parse_excluded_shipping_methods(excluded_methods)
@@ -209,36 +158,33 @@ def get_excluded_shipping_data(
def get_excluded_shipping_methods_from_response(
response_data: dict,
-) -> list[dict]:
+ webhook: "Webhook",
+) -> list[ExcludedShippingMethodSchema]:
excluded_methods = []
- for method_data in response_data.get("excluded_methods", []):
- try:
- type_name, method_id = from_global_id_or_error(method_data["id"])
- if type_name not in (APP_ID_PREFIX, str(ShippingMethod)):
- logger.warning(
- "Invalid type received. Expected ShippingMethod, got %s", type_name
- )
- continue
-
- except (KeyError, ValueError, TypeError, GraphQLError) as e:
- logger.warning("Malformed ShippingMethod id was provided: %s", e)
- continue
- excluded_methods.append(
- {"id": method_id, "reason": method_data.get("reason", "")}
+ try:
+ filter_methods_schema = FilterShippingMethodsSchema.model_validate(
+ response_data
+ )
+ excluded_methods.extend(filter_methods_schema.excluded_methods)
+ except ValidationError:
+ logger.warning(
+ "Skipping invalid response from app %s: %s",
+ str(webhook.app.identifier),
+ response_data,
)
return excluded_methods
def parse_excluded_shipping_methods(
- excluded_methods: list[dict],
+ excluded_methods: list[ExcludedShippingMethodSchema],
) -> dict[str, list[ExcludedShippingMethod]]:
+ """Prepare method_id to excluded methods map."""
excluded_methods_map = defaultdict(list)
for excluded_method in excluded_methods:
- method_id = excluded_method["id"]
+ method_id = excluded_method.id
+ reason = excluded_method.reason or ""
excluded_methods_map[method_id].append(
- ExcludedShippingMethod(
- id=method_id, reason=excluded_method.get("reason", "")
- )
+ ExcludedShippingMethod(id=method_id, reason=reason)
)
return excluded_methods_map
diff --git a/saleor/webhook/transport/shipping_helpers.py b/saleor/webhook/transport/shipping_helpers.py
new file mode 100644
index 0000000000..c8ba25fa4d
--- /dev/null
+++ b/saleor/webhook/transport/shipping_helpers.py
@@ -0,0 +1,32 @@
+import base64
+
+from ...app.models import App
+from ..const import APP_ID_PREFIX
+
+
+def to_shipping_app_id(app: App, shipping_method_id: str) -> str:
+ app_identifier = app.identifier or app.id
+ return base64.b64encode(
+ str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}")
+ ).decode("utf-8")
+
+
+def convert_to_app_id_with_identifier(shipping_app_id: str) -> None | str:
+ """Prepare the shipping_app_id in format `app:<app-identifier>:method_id>`.
+
+ The format of shipping_app_id has been changes so we need to support both of them.
+ This method is preparing the new shipping_app_id format based on assumptions
+ that right now the old one is used which is `app:<app-pk>:<method_id>`
+ """
+ decoded_id = base64.b64decode(shipping_app_id).decode()
+ splitted_id = decoded_id.split(":")
+ if len(splitted_id) != 3:
+ return None
+ try:
+ app_id = int(splitted_id[1])
+ except (TypeError, ValueError):
+ return None
+ app = App.objects.filter(id=app_id).first()
+ if app is None:
+ return None
+ return to_shipping_app_id(app, splitted_id[2])
diff --git a/saleor/webhook/transport/tests/test_shipping_helpers.py b/saleor/webhook/transport/tests/test_shipping_helpers.py
new file mode 100644
index 0000000000..3eed8ad96a
--- /dev/null
+++ b/saleor/webhook/transport/tests/test_shipping_helpers.py
@@ -0,0 +1,62 @@
+import base64
+
+from ..shipping_helpers import convert_to_app_id_with_identifier
+
+
+def test_convert_to_app_id_with_identifier_valid(app):
+ # given
+ method_id = "123"
+ shipping_app_id = base64.b64encode(str.encode(f"app:{app.pk}:{method_id}")).decode(
+ "utf-8"
+ )
+
+ # when
+ app_id_with_identifier = convert_to_app_id_with_identifier(shipping_app_id)
+
+ # then
+ assert app_id_with_identifier
+ assert (
+ base64.b64decode(app_id_with_identifier).decode()
+ == f"app:{app.identifier}:{method_id}"
+ )
+
+
+def test_convert_to_app_id_with_identifier_missing_shipping_id(app):
+ # given
+ shipping_app_id = base64.b64encode(str.encode(f"app:{app.pk}")).decode("utf-8")
+
+ # when
+ app_id_with_identifier = convert_to_app_id_with_identifier(shipping_app_id)
+
+ # then
+ assert app_id_with_identifier is None
+
+
+def test_convert_to_app_id_with_identifier_missing_app_for_given_id():
+ # given
+ method_id = "123"
+ app_id = 321
+ shipping_app_id = base64.b64encode(str.encode(f"app:{app_id}:{method_id}")).decode(
+ "utf-8"
+ )
+
+ # when
+ app_id_with_identifier = convert_to_app_id_with_identifier(shipping_app_id)
+
+ # then
+ assert app_id_with_identifier is None
+
+
+def test_convert_to_app_id_with_identifier_invalid_app_id():
+ # given
+ method_id = "123"
+ app_id = "xyz"
+ shipping_app_id = base64.b64encode(str.encode(f"app:{app_id}:{method_id}")).decode(
+ "utf-8"
+ )
+
+ # when
+ app_id_with_identifier = convert_to_app_id_with_identifier(shipping_app_id)
+
+ # then
+ assert app_id_with_identifier is None