Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Valid address items extension. (#15877)
Piotr Zabieglikeabdab146e11
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87fc80b90b..2361a109e1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,7 @@ All notable, unreleased changes to this project will be documented in this file.- Calculate order promotions in draft orders - #15459 by @zedzior- Prevent name overwriting of Product Variants when Updating Product Types - #15670 by @teddyondieki- Added support for the `BrokerProperties` custom header to webhooks to support Azure Service Bus - #15899 by @patrys+- Extend valid address values - #15877 by @zedzior# 3.19.0diff --git a/saleor/account/i18n.py b/saleor/account/i18n.pyindex 6d7c03082b..4b414d9801 100644--- a/saleor/account/i18n.py+++ b/saleor/account/i18n.py@@ -7,6 +7,7 @@ from django.forms import BoundFieldfrom django.forms.models import ModelFormMetaclassfrom django_countries import countries+from .i18n_valid_address_extension import VALID_ADDRESS_EXTENSION_MAPfrom .models import Addressfrom .validators import validate_possible_numberfrom .widgets import DatalistTextWidget@@ -179,6 +180,7 @@ class CountryAwareAddressForm(AddressForm):if street_address_1 or street_address_2:data["street_address"] = f"{street_address_1}\n{street_address_2}"+ self.substitute_invalid_values(data)normalized_data = i18naddress.normalize_address(data)if getattr(self, "enable_normalization", True):data = normalized_data@@ -191,6 +193,18 @@ class CountryAwareAddressForm(AddressForm):data = super().clean()return self.validate_address(data)+ @staticmethod+ def substitute_invalid_values(data):+ """Map invalid address names to the values accepted by i18naddress package."""+ country_code = data["country_code"]+ if not country_code:+ return+ if custom_names := VALID_ADDRESS_EXTENSION_MAP.get(country_code):+ for field_name, mapping in custom_names.items():+ actual_value = data.get(field_name, "").strip().lower()+ if actual_value in mapping:+ data[field_name] = mapping[actual_value]+def get_address_form_class(country_code):return COUNTRY_FORMS.get(country_code, AddressForm)diff --git a/saleor/account/i18n_valid_address_extension.py b/saleor/account/i18n_valid_address_extension.pynew file mode 100644index 0000000000..d906facae9--- /dev/null+++ b/saleor/account/i18n_valid_address_extension.py@@ -0,0 +1,45 @@+from enum import Enum++from ..graphql.account.enums import CountryCodeEnum+++class AddressFieldsToSubstitute(Enum):+ CITY_AREA = "city_area"+ COUNTRY_AREA = "country_area"+++IE_COUNTRY_AREA = {+ "Carlow": "Co. Carlow",+ "Cavan": "Co. Cavan",+ "Clare": "Co. Clare",+ "Cork": "Co. Cork",+ "Donegal": "Co. Donegal",+ "Dublin": "Co. Dublin",+ "Galway": "Co. Galway",+ "Kerry": "Co. Kerry",+ "Kildare": "Co. Kildare",+ "Kilkenny": "Co. Kilkenny",+ "Laois": "Co. Laois",+ "Leitrim": "Co. Leitrim",+ "Limerick": "Co. Limerick",+ "Longford": "Co. Longford",+ "Louth": "Co. Louth",+ "Mayo": "Co. Mayo",+ "Meath": "Co. Meath",+ "Monaghan": "Co. Monaghan",+ "Offaly": "Co. Offaly",+ "Roscommon": "Co. Roscommon",+ "Sligo": "Co. Sligo",+ "Tipperary": "Co. Tipperary",+ "Waterford": "Co. Waterford",+ "Westmeath": "Co. Westmeath",+ "Wexford": "Co. Wexford",+ "Wicklow": "Co. Wicklow",+}+IE_COUNTRY_AREA = {k.strip().lower(): v for k, v in IE_COUNTRY_AREA.items()}++VALID_ADDRESS_EXTENSION_MAP: dict[str, dict[str, dict[str, str]]] = {+ CountryCodeEnum.IE.value: {+ AddressFieldsToSubstitute.COUNTRY_AREA.value: IE_COUNTRY_AREA+ }+}diff --git a/saleor/account/tests/test_account.py b/saleor/account/tests/test_account.pyindex 57fb551452..e21b1b3226 100644--- a/saleor/account/tests/test_account.py+++ b/saleor/account/tests/test_account.py@@ -1,3 +1,4 @@+from unittest.mock import patchfrom urllib.parse import urlencodeimport i18naddress@@ -8,6 +9,7 @@ from django_countries.fields import Countryfrom ...order.models import Orderfrom .. import forms, i18n+from ..i18n_valid_address_extension import VALID_ADDRESS_EXTENSION_MAPfrom ..models import Userfrom ..validators import validate_possible_number@@ -312,3 +314,43 @@ def test_customers_show_staff_with_order(admin_user, channel_USD):channel=channel_USD,)assert User.objects.customers().count() == 1+++ ("country_area_input", "country_area_output", "is_valid"),+ [+ ("Dublin", "Co. Dublin", True),+ ("Co. Dublin", "Co. Dublin", True),+ ("Dummy Area", None, False),+ ("dublin", "Co. Dublin", True),+ (" dublin ", "Co. Dublin", True),+ ("", "", True),+ (None, "", True),+ ],+)+ VALID_ADDRESS_EXTENSION_MAP,+ {"IE": {"country_area": {"dublin": "Co. Dublin"}, "city_area": {"dummy": "dummy"}}},+)+def test_substitute_invalid_values(country_area_input, country_area_output, is_valid):+ # given+ data = {+ "first_name": "John",+ "last_name": "Doe",+ "country": "IE",+ "country_area": country_area_input,+ "city": "Dublin",+ "street_address_1": "1 Anglesea St",+ "postal_code": "D02 FK84",+ }++ # when+ form = forms.get_address_form(data, country_code="PL")+ errors = form.errors++ # then+ assert form.cleaned_data.get("country_area") == country_area_output+ if not is_valid:+ assert "country_area" in errors+ else:+ assert not errorsdiff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.pyindex 2c4b787283..ad118558ac 100644--- a/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py@@ -5,6 +5,7 @@ import grapheneimport pytestfrom django.utils.functional import SimpleLazyObject+from .....account.i18n_valid_address_extension import VALID_ADDRESS_EXTENSION_MAPfrom .....account.models import Addressfrom .....core.utils.json_serializer import CustomJsonEncoderfrom .....warehouse.error_codes import WarehouseErrorCode@@ -23,6 +24,7 @@ mutation createWarehouse($input: WarehouseCreateInput!) {externalReferenceaddress {id+ countryAreametadata {keyvalue@@ -341,3 +343,49 @@ def test_create_warehouse_with_non_unique_external_reference(assert error["field"] == "externalReference"assert error["code"] == WarehouseErrorCode.UNIQUE.nameassert error["message"] == "Warehouse with this External reference already exists."+++def test_create_warehouse_with_address_item_from_valid_address_extension_map(+ staff_api_client, permission_manage_products, shipping_zone+):+ # given+ country_area = "dublin"+ cleaned_country_area = "Co. Dublin"+ address = {+ "country": "IE",+ "countryArea": country_area,+ "streetAddress1": "1 Anglesea St",+ "postalCode": "D02 FK84",+ "city": "Dublin",+ }++ ireland_country_areas_extension = VALID_ADDRESS_EXTENSION_MAP["IE"]["country_area"]+ assert country_area in ireland_country_areas_extension+ assert ireland_country_areas_extension[country_area] == cleaned_country_area++ variables = {+ "input": {+ "name": "Test warehouse",+ "slug": "test-warhouse",+ "email": "[email protected]",+ "address": address,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_CREATE_WAREHOUSE,+ variables=variables,+ permissions=[permission_manage_products],+ )++ # then+ content = get_graphql_content(response)+ assert not content["data"]["createWarehouse"]["errors"]+ assert Warehouse.objects.count() == 1++ address = content["data"]["createWarehouse"]["warehouse"]["address"]+ assert address["countryArea"] == cleaned_country_area++ address_db = Warehouse.objects.first().address+ assert address_db.country_area == cleaned_country_area