Skip to content

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

Introduce numeric attributes (#6790)

Iga Karbowiaka6ec463c8898
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 19163faba9..3e328367e1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -165,6 +165,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Introduce product reference attributes - #6711 by @IKarbowiak
- Add metadata to warehouse - #6727 by @d-wysocki
- Add page webhooks: `PAGE_CREATED`, `PAGE_UPDATED` and `PAGE_DELETED` - #6787 by @d-wysocki
+- Introduce numeric attributes - #6790 by @IKarbowiak
- Add `PRODUCT_DELETED` webhook - #6794 by @d-wysocki
- Fix `product_updated` and `product_created` webhooks - #6798 by @d-wysocki
- Add interface for integrating the auth plugins - #6799 by @korycins
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
index d37d14f6ad..e2e17b6152 100644
--- a/saleor/attribute/__init__.py
+++ b/saleor/attribute/__init__.py
@@ -8,6 +8,7 @@ class AttributeInputType:
MULTISELECT = "multiselect"
FILE = "file"
REFERENCE = "reference"
+ NUMERIC = "numeric"
RICH_TEXT = "rich-text"
CHOICES = [
@@ -15,12 +16,37 @@ class AttributeInputType:
(MULTISELECT, "Multi Select"),
(FILE, "File"),
(REFERENCE, "Reference"),
+ (NUMERIC, "Numeric"),
(RICH_TEXT, "Rich Text"),
]
# list of the input types that can be used in variant selection
ALLOWED_IN_VARIANT_SELECTION = [DROPDOWN]
+# list of input types that are allowed for given attribute property
+ATTRIBUTE_PROPERTIES_CONFIGURATION = {
+ "filterable_in_storefront": [
+ AttributeInputType.DROPDOWN,
+ AttributeInputType.MULTISELECT,
+ AttributeInputType.NUMERIC,
+ ],
+ "filterable_in_dashboard": [
+ AttributeInputType.DROPDOWN,
+ AttributeInputType.MULTISELECT,
+ AttributeInputType.NUMERIC,
+ ],
+ "available_in_grid": [
+ AttributeInputType.DROPDOWN,
+ AttributeInputType.MULTISELECT,
+ AttributeInputType.NUMERIC,
+ ],
+ "storefront_search_position": [
+ AttributeInputType.DROPDOWN,
+ AttributeInputType.MULTISELECT,
+ ],
+}
+
+
class AttributeType:
PRODUCT_TYPE = "product-type"
PAGE_TYPE = "page-type"
diff --git a/saleor/attribute/migrations/0010_auto_20210412_0736.py b/saleor/attribute/migrations/0010_auto_20210412_0736.py
new file mode 100644
index 0000000000..161b680785
--- /dev/null
+++ b/saleor/attribute/migrations/0010_auto_20210412_0736.py
@@ -0,0 +1,68 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0009_auto_20210421_0552"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attribute",
+ name="unit",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("cm", "cm"),
+ ("m", "m"),
+ ("km", "km"),
+ ("ft", "ft"),
+ ("yd", "yd"),
+ ("inch", "inch"),
+ ("sq_cm", "sq_cm"),
+ ("sq_m", "sq_m"),
+ ("sq_km", "sq_km"),
+ ("sq_ft", "sq_ft"),
+ ("sq_yd", "sq_yd"),
+ ("sq_inch", "sq_inch"),
+ ("cubic_millimeter", "cubic_millimeter"),
+ ("cubic_centimeter", "cubic_centimeter"),
+ ("cubic_decimeter", "cubic_decimeter"),
+ ("cubic_meter", "cubic_meter"),
+ ("liter", "liter"),
+ ("cubic_foot", "cubic_foot"),
+ ("cubic_inch", "cubic_inch"),
+ ("cubic_yard", "cubic_yard"),
+ ("qt", "qt"),
+ ("pint", "pint"),
+ ("fl_oz", "fl_oz"),
+ ("acre_in", "acre_in"),
+ ("acre_ft", "acre_ft"),
+ ("g", "g"),
+ ("lb", "lb"),
+ ("oz", "oz"),
+ ("kg", "kg"),
+ ("tonne", "tonne"),
+ ],
+ max_length=100,
+ null=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="attribute",
+ name="input_type",
+ field=models.CharField(
+ choices=[
+ ("dropdown", "Dropdown"),
+ ("multiselect", "Multi Select"),
+ ("file", "File"),
+ ("reference", "Reference"),
+ ("numeric", "Numeric"),
+ ("rich-text", "Rich Text"),
+ ],
+ default="dropdown",
+ max_length=50,
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 432c09e995..0d82c43ab8 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -6,6 +6,7 @@ from django.db.models import F, Q
from ...account.utils import requestor_is_staff_member_or_app
from ...core.db.fields import SanitizedJSONField
from ...core.models import ModelWithMetadata, SortableModel
+from ...core.units import MeasurementUnits
from ...core.utils.editorjs import clean_editor_js
from ...core.utils.translations import TranslationProxy
from ...page.models import PageType
@@ -136,6 +137,12 @@ class Attribute(ModelWithMetadata):
through_fields=("attribute", "page_type"),
)
+ unit = models.CharField(
+ max_length=100,
+ choices=MeasurementUnits.CHOICES, # type: ignore
+ blank=True,
+ null=True,
+ )
value_required = models.BooleanField(default=False, blank=True)
is_variant_only = models.BooleanField(default=False, blank=True)
visible_in_storefront = models.BooleanField(default=True, blank=True)
diff --git a/saleor/core/tests/test_weight.py b/saleor/core/tests/test_weight.py
index 81c1733edf..772872ce27 100644
--- a/saleor/core/tests/test_weight.py
+++ b/saleor/core/tests/test_weight.py
@@ -1,8 +1,8 @@
import pytest
from measurement.measures import Weight
+from ..units import WeightUnits
from ..weight import (
- WeightUnits,
convert_weight,
convert_weight_to_default_weight_unit,
get_default_weight_unit,
@@ -15,7 +15,7 @@ def test_convert_weight():
expected_result = Weight(g=1000)
# when
- result = convert_weight(weight, WeightUnits.GRAM)
+ result = convert_weight(weight, WeightUnits.G)
# then
assert result == expected_result
@@ -32,10 +32,10 @@ def test_get_default_weight_unit(site_settings):
@pytest.mark.parametrize(
"default_weight_unit, expected_value",
[
- (WeightUnits.KILOGRAM, Weight(kg=1)),
- (WeightUnits.GRAM, Weight(g=1000)),
- (WeightUnits.POUND, Weight(lb=2.205)),
- (WeightUnits.OUNCE, Weight(oz=35.274)),
+ (WeightUnits.KG, Weight(kg=1)),
+ (WeightUnits.G, Weight(g=1000)),
+ (WeightUnits.LB, Weight(lb=2.205)),
+ (WeightUnits.OZ, Weight(oz=35.274)),
],
)
def test_convert_weight_to_default_weight_unit(
diff --git a/saleor/core/units.py b/saleor/core/units.py
new file mode 100644
index 0000000000..a4c58a7677
--- /dev/null
+++ b/saleor/core/units.py
@@ -0,0 +1,95 @@
+class DistanceUnits:
+ CM = "cm"
+ M = "m"
+ KM = "km"
+ FT = "ft"
+ YD = "yd"
+ INCH = "inch"
+
+ CHOICES = [
+ (CM, "Centimeter"),
+ (M, "Meter"),
+ (KM, "Kilometers"),
+ (FT, "Feet"),
+ (YD, "Yard"),
+ (INCH, "Inch"),
+ ]
+
+
+class AreaUnits:
+ SQ_CM = "sq_cm"
+ SQ_M = "sq_m"
+ SQ_KM = "sq_km"
+ SQ_FT = "sq_ft"
+ SQ_YD = "sq_yd"
+ SQ_INCH = "sq_inch"
+
+ CHOICES = [
+ (SQ_CM, "Square centimeters"),
+ (SQ_M, "Square meters"),
+ (SQ_KM, "Square kilometers"),
+ (SQ_FT, "Square feet"),
+ (SQ_YD, "Square yards"),
+ (SQ_INCH, "Square inches"),
+ ]
+
+
+class VolumeUnits:
+ CUBIC_MILLIMETER = "cubic_millimeter"
+ CUBIC_CENTIMETER = "cubic_centimeter"
+ CUBIC_DECIMETER = "cubic_decimeter"
+ CUBIC_METER = "cubic_meter"
+ LITER = "liter"
+ CUBIC_FOOT = "cubic_foot"
+ CUBIC_INCH = "cubic_inch"
+ CUBIC_YARD = "cubic_yard"
+ QT = "qt"
+ PINT = "pint"
+ FL_OZ = "fl_oz"
+ ACRE_IN = "acre_in"
+ ACRE_FT = "acre_ft"
+
+ CHOICES = [
+ (CUBIC_MILLIMETER, "Cubic millimeter"),
+ (CUBIC_CENTIMETER, "Cubic centimeter"),
+ (CUBIC_DECIMETER, "Cubic decimeter"),
+ (CUBIC_METER, "Cubic meter"),
+ (LITER, "Liter"),
+ (CUBIC_FOOT, "Cubic foot"),
+ (CUBIC_INCH, "Cubic inch"),
+ (CUBIC_YARD, "Cubic yard"),
+ (QT, "Quart"),
+ (PINT, "Pint"),
+ (FL_OZ, "Fluid ounce"),
+ (ACRE_IN, "Acre inch"),
+ (ACRE_FT, "Acre feet"),
+ ]
+
+
+class WeightUnits:
+ G = "g"
+ LB = "lb"
+ OZ = "oz"
+ KG = "kg"
+ TONNE = "tonne"
+
+ CHOICES = [
+ (G, "Gram"),
+ (LB, "Pound"),
+ (OZ, "Ounce"),
+ (KG, "kg"),
+ (TONNE, "Tonne"),
+ ]
+
+
+def prepare_all_units_dict():
+ measurement_dict = {
+ unit.upper(): unit
+ for units in [DistanceUnits, AreaUnits, VolumeUnits, WeightUnits]
+ for unit, _ in units.CHOICES
+ }
+ measurement_dict["CHOICES"] = [(v, v) for v in measurement_dict.values()]
+ return measurement_dict
+
+
+MeasurementUnits = type("MeasurementUnits", (object,), prepare_all_units_dict())
diff --git a/saleor/core/weight.py b/saleor/core/weight.py
index 8402a9c009..7f052b512e 100644
--- a/saleor/core/weight.py
+++ b/saleor/core/weight.py
@@ -16,20 +16,6 @@ from django.contrib.sites.models import Site
from measurement.measures import Weight
-class WeightUnits:
- KILOGRAM = "kg"
- POUND = "lb"
- OUNCE = "oz"
- GRAM = "g"
-
- CHOICES = [
- (KILOGRAM, "kg"),
- (POUND, "lb"),
- (OUNCE, "oz"),
- (GRAM, "g"),
- ]
-
-
def zero_weight():
"""Represent the zero weight value."""
return Weight(kg=0)
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index cfe513ea89..44b366199a 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -81,9 +81,7 @@ def test_get_products_data(product, product_with_image, collection, image, chann
else product.collections.first().slug
),
"product_weight": (
- "{} g".format(int(product.weight.value * 1000))
- if product.weight
- else ""
+ "{} g".format(int(product.weight.value)) if product.weight else ""
),
"media__image": (
""
@@ -108,9 +106,7 @@ def test_get_products_data(product, product_with_image, collection, image, chann
else "http://mirumee.com{}".format(variant.media.first().image.url)
),
"variant_weight": (
- "{} g".foramt(int(variant.weight.value * 1000))
- if variant.weight
- else ""
+ "{} g".foramt(int(variant.weight.value)) if variant.weight else ""
),
}
data.update(product_data)
@@ -239,6 +235,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ numeric_attribute,
product_with_image,
product_with_variant_with_two_attributes,
rich_text_attribute,
@@ -251,23 +248,17 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
file_attribute,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ numeric_attribute,
rich_text_attribute,
)
product.product_type.product_attributes.add(
file_attribute,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ numeric_attribute,
rich_text_attribute,
)
- # add file attribute
- associate_attribute_values_to_instance(
- variant_with_many_stocks, file_attribute, file_attribute.values.first()
- )
- associate_attribute_values_to_instance(
- product, file_attribute, file_attribute.values.first()
- )
-
# add rich text attribute
associate_attribute_values_to_instance(
variant_with_many_stocks,
@@ -321,6 +312,15 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product, product_type_product_reference_attribute, product_product_ref_value
)
+ # add numeric attribute
+ numeric_value_1 = numeric_attribute.values.first()
+ numeric_value_2 = numeric_attribute.values.last()
+
+ associate_attribute_values_to_instance(
+ variant_with_many_stocks, numeric_attribute, numeric_value_1
+ )
+ associate_attribute_values_to_instance(product, numeric_attribute, numeric_value_2)
+
# create assigned product without values
associate_attribute_values_to_instance(
product, color_attribute, color_attribute.values.first()
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index aa3e64a77a..ce80bbc3ac 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -797,6 +797,7 @@ def test_add_attribute_info_to_data(product):
file_url=None,
input_type="dropdown",
entity_type=None,
+ unit=None,
rich_text=None,
)
input_data = {pk: {}}
@@ -824,6 +825,7 @@ def test_add_attribute_info_to_data_update_attribute_data(product):
file_url=None,
input_type="dropdown",
entity_type=None,
+ unit=None,
rich_text=None,
)
input_data = {pk: {expected_header: {"value1"}}}
@@ -846,6 +848,7 @@ def test_add_attribute_info_to_data_no_slug(product):
file_url=None,
input_type="dropdown",
entity_type=None,
+ unit=None,
rich_text=None,
)
input_data = {pk: {}}
@@ -870,6 +873,7 @@ def test_add_attribute_info_when_no_value(product):
input_type="dropdown",
entity_type=None,
rich_text=None,
+ unit=None,
)
input_data = {pk: {}}
@@ -894,6 +898,7 @@ def test_add_file_attribute_info_to_data(product):
file_url=test_url,
input_type="file",
entity_type=None,
+ unit=None,
rich_text=None,
)
input_data = {pk: {}}
@@ -918,6 +923,7 @@ def test_add_rich_text_attribute_info_to_data(product):
file_url=None,
input_type="rich-text",
entity_type=None,
+ unit=None,
rich_text=dummy_editorjs("Dummy"),
)
input_data = {pk: {}}
@@ -943,6 +949,7 @@ def test_add_reference_attribute_info_to_data(product, page):
file_url=None,
input_type="reference",
entity_type="Page",
+ unit=None,
rich_text="None",
)
input_data = {pk: {}}
@@ -971,6 +978,7 @@ def test_add_reference_info_to_data_update_attribute_data(product, page):
file_url=None,
input_type="reference",
entity_type="Page",
+ unit=None,
rich_text=None,
)
input_data = {pk: {expected_header: values}}
@@ -985,6 +993,56 @@ def test_add_reference_info_to_data_update_attribute_data(product, page):
assert result[pk][expected_header] == values
+def test_add_numeric_attribute_info_to_data(product, numeric_attribute):
+ # given
+ pk = product.pk
+ value = "12.3"
+ attribute_data = AttributeData(
+ slug=numeric_attribute.slug,
+ value=value,
+ file_url=None,
+ input_type="numeric",
+ entity_type=None,
+ unit=numeric_attribute.unit,
+ rich_text=None,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{numeric_attribute.slug} (product attribute)"
+ assert result[pk][expected_header] == {f"{value} {numeric_attribute.unit}"}
+
+
+def test_add_numeric_attribute_info_to_data_no_unit(product, numeric_attribute):
+ # given
+ pk = product.pk
+ value = "12.3"
+ attribute_data = AttributeData(
+ slug=numeric_attribute.slug,
+ value=value,
+ file_url=None,
+ input_type="numeric",
+ entity_type=None,
+ unit=None,
+ rich_text=None,
+ )
+ input_data = {pk: {}}
+
+ # when
+ result = add_attribute_info_to_data(
+ product.pk, attribute_data, "product attribute", input_data
+ )
+
+ # then
+ expected_header = f"{numeric_attribute.slug} (product attribute)"
+ assert result[pk][expected_header] == {value}
+
+
def test_add_attribute_info_to_data_no_file_url_for_file_attribute(product):
# given
pk = product.pk
@@ -997,6 +1055,7 @@ def test_add_attribute_info_to_data_no_file_url_for_file_attribute(product):
input_type="file",
entity_type=None,
rich_text=None,
+ unit=None,
)
input_data = {pk: {}}
@@ -1022,6 +1081,7 @@ def test_add_attribute_info_to_data_no_rich_text_for_rich_text_attribute(product
input_type="rich-text",
entity_type=None,
rich_text=None,
+ unit=None,
)
input_data = {pk: {}}
@@ -1046,6 +1106,7 @@ def test_add_attribute_info_to_data_no_value_for_reference_attribute(product):
input_type="reference",
entity_type=None,
rich_text=None,
+ unit=None,
)
input_data = {pk: {}}
diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.py
index b8f72f9387..67e66095a0 100644
--- a/saleor/csv/tests/export/products_data/utils.py
+++ b/saleor/csv/tests/export/products_data/utils.py
@@ -38,6 +38,10 @@ def get_attribute_value(assigned_attribute):
elif attribute.input_type == AttributeInputType.REFERENCE:
ref_id = value_instance.slug.split("_")[1]
value = f"{attribute.entity_type}_{ref_id}"
+ elif attribute.input_type == AttributeInputType.NUMERIC:
+ value = f"{value_instance.name}"
+ if attribute.unit:
+ value += f" {attribute.unit}"
elif attribute.input_type == AttributeInputType.RICH_TEXT:
value = clean_editor_js(value_instance.rich_text, to_string=True)
else:
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index b8be169129..0f157a750b 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -27,6 +27,7 @@ class ProductExportFields:
"slug": "attributes__assignment__attribute__slug",
"input_type": "attributes__assignment__attribute__input_type",
"entity_type": "attributes__assignment__attribute__entity_type",
+ "unit": "attributes__assignment__attribute__unit",
"attribute_pk": "attributes__assignment__attribute__pk",
}
@@ -53,6 +54,7 @@ class ProductExportFields:
"slug": "variants__attributes__assignment__attribute__slug",
"input_type": "variants__attributes__assignment__attribute__input_type",
"entity_type": "variants__attributes__assignment__attribute__entity_type",
+ "unit": "variants__attributes__assignment__attribute__unit",
"attribute_pk": "variants__attributes__assignment__attribute__pk",
}
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 1de82bc544..138a5e3551 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -293,7 +293,7 @@ def add_image_uris_to_data(
AttributeData = namedtuple(
"AttributeData",
- ["slug", "file_url", "value", "input_type", "entity_type", "rich_text"],
+ ["slug", "file_url", "value", "input_type", "entity_type", "unit", "rich_text"],
)
@@ -312,6 +312,7 @@ def handle_attribute_data(
file_url=data.pop(attribute_fields["file_url"], None),
value=data.pop(attribute_fields["value"], None),
entity_type=data.pop(attribute_fields["entity_type"], None),
+ unit=data.pop(attribute_fields["unit"], None),
rich_text=data.pop(attribute_fields["rich_text"], None),
)
@@ -398,6 +399,10 @@ def add_attribute_info_to_data(
elif input_type == AttributeInputType.REFERENCE and attribute_data.value:
reference_id = attribute_data.value.split("_")[1]
value = f"{attribute_data.entity_type}_{reference_id}"
+ elif input_type == AttributeInputType.NUMERIC:
+ value = f"{attribute_data.value}"
+ if attribute_data.unit:
+ value += f" {attribute_data.unit}"
elif input_type == AttributeInputType.RICH_TEXT:
value = clean_editor_js(attribute_data.rich_text, to_string=True)
else:
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 059395a781..4b2d58ecdb 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -5,6 +5,7 @@ from .app.schema import AppMutations, AppQueries
from .attribute.schema import AttributeMutations, AttributeQueries
from .channel.schema import ChannelMutations, ChannelQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
+from .core.enums import unit_enums
from .core.schema import CoreMutations, CoreQueries
from .csv.schema import CsvMutations, CsvQueries
from .discount.schema import DiscountMutations, DiscountQueries
@@ -76,4 +77,4 @@ class Mutation(
pass
-schema = build_schema(Query, mutation=Mutation)
+schema = build_schema(Query, mutation=Mutation, types=unit_enums)
diff --git a/saleor/graphql/attribute/descriptions.py b/saleor/graphql/attribute/descriptions.py
index 6d0d79443e..9070e9c132 100644
--- a/saleor/graphql/attribute/descriptions.py
+++ b/saleor/graphql/attribute/descriptions.py
@@ -4,6 +4,7 @@ class AttributeDescriptions:
NAME = "Name of an attribute displayed in the interface."
SLUG = "Internal representation of an attribute name."
TYPE = "The attribute type."
+ UNIT = "The unit of attribute values."
VALUES = "List of attribute's values."
VALUE_REQUIRED = "Whether the attribute requires values to be passed or not."
IS_VARIANT_ONLY = "Whether the attribute is for variants only."
@@ -26,5 +27,6 @@ class AttributeValueDescriptions:
SLUG = "Internal representation of a value (unique per attribute)."
TYPE = "Type of value (used only when `value` field is set)."
FILE = "Represents file URL and content type (if attribute value is a file)."
+ VALUES_RANGE = "The range that the returned values should be in."
VALUE = "Represents the value of the attribute value."
RICH_TEXT = "Represents the text (JSON) of the attribute value."
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
index 433e77cbcd..767094f2ce 100644
--- a/saleor/graphql/attribute/mutations.py
+++ b/saleor/graphql/attribute/mutations.py
@@ -5,7 +5,7 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from django.utils.text import slugify
-from ...attribute import AttributeInputType
+from ...attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputType
from ...attribute import models as models
from ...attribute.error_codes import AttributeErrorCode
from ...core.exceptions import PermissionDenied
@@ -15,6 +15,7 @@ from ...core.permissions import (
ProductTypePermissions,
)
from ..attribute.types import Attribute, AttributeValue
+from ..core.enums import MeasurementUnitsEnum
from ..core.inputs import ReorderInput
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import AttributeError
@@ -196,6 +197,7 @@ class AttributeCreateInput(graphene.InputObjectType):
name = graphene.String(required=True, description=AttributeDescriptions.NAME)
slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)
type = AttributeTypeEnum(description=AttributeDescriptions.TYPE, required=True)
+ unit = MeasurementUnitsEnum(description=AttributeDescriptions.UNIT, required=False)
values = graphene.List(
AttributeValueCreateInput, description=AttributeDescriptions.VALUES
)
@@ -223,6 +225,7 @@ class AttributeCreateInput(graphene.InputObjectType):
class AttributeUpdateInput(graphene.InputObjectType):
name = graphene.String(description=AttributeDescriptions.NAME)
slug = graphene.String(description=AttributeDescriptions.SLUG)
+ unit = MeasurementUnitsEnum(description=AttributeDescriptions.UNIT, required=False)
remove_values = graphene.List(
graphene.ID,
name="removeValues",
@@ -317,8 +320,14 @@ class AttributeMixin:
}
)
+ is_numeric_attr = attribute_input_type == AttributeInputType.NUMERIC
for value_data in values_input:
- value_data["slug"] = slugify(value_data["name"], allow_unicode=True)
+ value = value_data["name"]
+ if is_numeric_attr:
+ cls.validate_numeric_value(value)
+ slug_value = value if not is_numeric_attr else value.replace(".", "_")
+ value_data["slug"] = slugify(slug_value, allow_unicode=True)
+
attribute_value = models.AttributeValue(**value_data, attribute=attribute)
try:
attribute_value.full_clean()
@@ -329,6 +338,20 @@ class AttributeMixin:
raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: err})
cls.check_values_are_unique(values_input, attribute)
+ @classmethod
+ def validate_numeric_value(cls, value):
+ try:
+ float(value)
+ except ValueError:
+ raise ValidationError(
+ {
+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
+ "Value of numeric attribute must be numeric.",
+ code=AttributeErrorCode.INVALID,
+ )
+ }
+ )
+
@classmethod
def clean_attribute(cls, instance, cleaned_input):
try:
@@ -349,21 +372,14 @@ class AttributeMixin:
Ensure that any invalid operations will be not performed.
"""
attribute_input_type = cleaned_input.get("input_type") or instance.input_type
- if attribute_input_type not in [
- AttributeInputType.FILE,
- AttributeInputType.REFERENCE,
- ]:
- return
errors = {}
- for field in [
- "filterable_in_storefront",
- "filterable_in_dashboard",
- "available_in_grid",
- "storefront_search_position",
- ]:
- if cleaned_input.get(field):
+ for field in ATTRIBUTE_PROPERTIES_CONFIGURATION.keys():
+ allowed_input_type = ATTRIBUTE_PROPERTIES_CONFIGURATION[field]
+ if attribute_input_type not in allowed_input_type and cleaned_input.get(
+ field
+ ):
errors[field] = ValidationError(
- f"Cannot set on a {attribute_input_type} attribute.",
+ f"Cannot set {field} on a {attribute_input_type} attribute.",
code=AttributeErrorCode.INVALID.value,
)
if errors:
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
index c828f036a5..65aa0bb167 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
@@ -2,6 +2,7 @@ import pytest
from django.utils.text import slugify
from .....attribute.error_codes import AttributeErrorCode
+from ....core.enums import MeasurementUnitsEnum
from ....tests.utils import get_graphql_content
from ...enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
@@ -19,6 +20,7 @@ CREATE_ATTRIBUTE_MUTATION = """
name
slug
type
+ unit
inputType
entityType
filterableInStorefront
@@ -94,6 +96,110 @@ def test_create_attribute_and_attribute_values(
assert data["attribute"]["values"][0]["value"] == value
+def test_create_numeric_attribute_and_attribute_values(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Example numeric attribute name"
+ name = "12.1"
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "values": [{"name": name}],
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "unit": MeasurementUnitsEnum.M.name,
+ "inputType": AttributeInputTypeEnum.NUMERIC.name,
+ "filterableInStorefront": True,
+ "filterableInDashboard": True,
+ "availableInGrid": True,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["errors"]
+ data = content["data"]["attributeCreate"]
+
+ # Check if the attribute was correctly created
+ assert data["attribute"]["name"] == attribute_name
+ assert data["attribute"]["slug"] == slugify(
+ attribute_name
+ ), "The default slug should be the slugified name"
+ assert (
+ data["attribute"]["productTypes"]["edges"] == []
+ ), "The attribute should not have been assigned to a product type"
+
+ # Check if the attribute values were correctly created
+ assert len(data["attribute"]["values"]) == 1
+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name
+ assert data["attribute"]["unit"] == MeasurementUnitsEnum.M.name
+ assert data["attribute"]["inputType"] == AttributeInputTypeEnum.NUMERIC.name
+ assert data["attribute"]["filterableInStorefront"] is True
+ assert data["attribute"]["filterableInDashboard"] is True
+ assert data["attribute"]["availableInGrid"] is True
+ assert data["attribute"]["storefrontSearchPosition"] == 0
+ assert data["attribute"]["values"][0]["name"] == name
+ assert data["attribute"]["values"][0]["slug"] == slugify(name.replace(".", "_"))
+
+
+def test_create_numeric_attribute_and_attribute_values_not_numeric_value_provided(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Example numeric attribute name"
+ name = "Width"
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "values": [{"name": name}],
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "unit": MeasurementUnitsEnum.M.name,
+ "inputType": AttributeInputTypeEnum.NUMERIC.name,
+ "filterableInStorefront": True,
+ "filterableInDashboard": True,
+ "availableInGrid": True,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeCreate"]
+ errors = content["data"]["attributeCreate"]["errors"]
+
+ assert not data["attribute"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "values"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
def test_create_attribute_with_file_input_type(
staff_api_client,
permission_manage_product_types_and_attributes,
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
index 965a0e2959..f3225d6248 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
@@ -3,6 +3,7 @@ import pytest
from .....attribute.error_codes import AttributeErrorCode
from .....attribute.models import Attribute
+from ....core.enums import MeasurementUnitsEnum
from ....tests.utils import get_graphql_content
UPDATE_ATTRIBUTE_MUTATION = """
@@ -20,6 +21,7 @@ UPDATE_ATTRIBUTE_MUTATION = """
attribute {
name
slug
+ unit
values {
name
slug
@@ -161,6 +163,39 @@ def test_update_attribute_with_file_input_type(
assert data["attribute"]["name"] == name == attribute.name
+def test_update_attribute_with_numeric_input_type(
+ staff_api_client,
+ numeric_attribute,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = numeric_attribute
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+
+ name = "Weight"
+ slug = "weight"
+ unit = MeasurementUnitsEnum.G.name
+ variables = {
+ "id": node_id,
+ "input": {"name": name, "slug": slug, "unit": unit},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute.refresh_from_db()
+ data = content["data"]["attributeUpdate"]
+ assert not data["errors"]
+ assert data["attribute"]["name"] == name
+ assert data["attribute"]["slug"] == slug
+ assert data["attribute"]["unit"] == unit
+
+
def test_update_attribute_with_file_input_type_and_values(
staff_api_client,
file_attribute_with_file_input_type_without_values,
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
index 05dadbabb6..c43c45f434 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
@@ -66,6 +66,7 @@ query($id: ID!) {
inputType
entityType
type
+ unit
values {
slug
inputType
@@ -297,6 +298,50 @@ def test_get_single_reference_attribute_by_staff(
)
+def test_get_single_numeric_attribute_by_staff(
+ staff_api_client, numeric_attribute, permission_manage_products
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ attribute_gql_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)
+ query = QUERY_ATTRIBUTE
+ content = get_graphql_content(
+ staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+ )
+
+ assert content["data"]["attribute"], "Should have found an attribute"
+ assert content["data"]["attribute"]["id"] == attribute_gql_id
+ assert content["data"]["attribute"]["slug"] == numeric_attribute.slug
+ assert (
+ content["data"]["attribute"]["inputType"]
+ == numeric_attribute.input_type.upper()
+ )
+ assert content["data"]["attribute"]["unit"] == numeric_attribute.unit.upper()
+ assert (
+ content["data"]["attribute"]["valueRequired"]
+ == numeric_attribute.value_required
+ )
+ assert (
+ content["data"]["attribute"]["visibleInStorefront"]
+ == numeric_attribute.visible_in_storefront
+ )
+ assert (
+ content["data"]["attribute"]["filterableInStorefront"]
+ == numeric_attribute.filterable_in_storefront
+ )
+ assert (
+ content["data"]["attribute"]["filterableInDashboard"]
+ == numeric_attribute.filterable_in_dashboard
+ )
+ assert (
+ content["data"]["attribute"]["availableInGrid"]
+ == numeric_attribute.available_in_grid
+ )
+ assert (
+ content["data"]["attribute"]["storefrontSearchPosition"]
+ == numeric_attribute.storefront_search_position
+ )
+
+
QUERY_ATTRIBUTES = """
query {
attributes(first: 20) {
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index ad5ee64050..db6d74de38 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -1,4 +1,5 @@
import graphene
+import pytest
from ....attribute import AttributeInputType
from ....page.error_codes import PageErrorCode
@@ -1078,3 +1079,145 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(
assert set(error.params["attributes"]) == {
graphene.Node.to_global_id("Attribute", file_attribute.pk)
}
+
+
+def test_validate_numeric_attributes_input_for_product(numeric_attribute, product_type):
+ # given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ numeric_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ values=["12.34"],
+ file_url=None,
+ content_type=None,
+ references=[],
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ variant_validation=False,
+ )
+
+ # then
+ assert not errors
+
+
[email protected]("value", ["qvd", "12.se", " "])
+def test_validate_numeric_attributes_input_for_product_not_numeric_value_given(
+ value, numeric_attribute, product_type
+):
+ # given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ numeric_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ values=[value],
+ file_url=None,
+ content_type=None,
+ references=[],
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ variant_validation=False,
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ }
+
+
+def test_validate_numeric_attributes_input_for_product_blank_value(
+ numeric_attribute, product_type
+):
+ # given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ numeric_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ values=[None],
+ file_url=None,
+ content_type=None,
+ references=[],
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ variant_validation=False,
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ }
+
+
+def test_validate_numeric_attributes_input_for_product_more_than_one_value_given(
+ numeric_attribute, product_type
+):
+ # given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ numeric_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ values=["12", 1, 123],
+ file_url=None,
+ content_type=None,
+ references=[],
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ variant_validation=False,
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == ProductErrorCode.INVALID.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ }
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 948b51278b..7315e303d1 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -5,7 +5,9 @@ import graphene
from ...attribute import AttributeInputType, models
from ...core.tracing import traced_resolver
from ..core.connection import CountableDjangoObjectType
+from ..core.enums import MeasurementUnitsEnum
from ..core.types import File
+from ..core.types.common import IntRangeInput
from ..decorators import (
check_attribute_required_permissions,
check_attribute_value_required_permissions,
@@ -84,6 +86,7 @@ class Attribute(CountableDjangoObjectType):
name = graphene.String(description=AttributeDescriptions.NAME)
slug = graphene.String(description=AttributeDescriptions.SLUG)
type = AttributeTypeEnum(description=AttributeDescriptions.TYPE)
+ unit = MeasurementUnitsEnum(description=AttributeDescriptions.UNIT)
values = graphene.List(AttributeValue, description=AttributeDescriptions.VALUES)
@@ -174,3 +177,33 @@ class AttributeInput(graphene.InputObjectType):
values = graphene.List(
graphene.String, required=False, description=AttributeValueDescriptions.SLUG
)
+ values_range = graphene.Field(
+ IntRangeInput,
+ required=False,
+ description=AttributeValueDescriptions.VALUES_RANGE,
+ )
+
+
+class AttributeValueInput(graphene.InputObjectType):
+ id = graphene.ID(description="ID of the selected attribute.")
+ values = graphene.List(
+ graphene.String,
+ required=False,
+ description=(
+ "The value or slug of an attribute to resolve. "
+ "If the passed value is non-existent, it will be created."
+ ),
+ )
+ file = graphene.String(
+ required=False,
+ description="URL of the file attribute. Every time, a new value is created.",
+ )
+ content_type = graphene.String(required=False, description="File content type.")
+ references = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of entity IDs that will be used as references.",
+ required=False,
+ )
+ rich_text = graphene.JSONString(
+ required=False, description="Text content in JSON format."
+ )
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index 81cde8801c..3aa78875d6 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -134,6 +134,7 @@ class AttributeAssignmentMixin:
):
"""Lazy-retrieve or create the database objects from the supplied raw values."""
get_or_create = attribute.values.get_or_create
+
return tuple(
get_or_create(
attribute=attribute,
@@ -143,6 +144,49 @@ class AttributeAssignmentMixin:
for value in attr_values.values
)
+ @classmethod
+ def _pre_save_numeric_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ defaults = {
+ "name": attr_values.values[0],
+ }
+ return cls._update_or_create_value(instance, attribute, defaults)
+
+ @classmethod
+ def _pre_save_rich_text_values(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ attr_values: AttrValuesInput,
+ ):
+ defaults = {
+ "rich_text": attr_values.rich_text,
+ "name": truncatechars(
+ clean_editor_js(attr_values.rich_text, to_string=True), 50
+ ),
+ }
+ return cls._update_or_create_value(instance, attribute, defaults)
+
+ @classmethod
+ def _update_or_create_value(
+ cls,
+ instance: T_INSTANCE,
+ attribute: attribute_models.Attribute,
+ value_defaults: dict,
+ ):
+ update_or_create = attribute.values.update_or_create
+ slug = slugify(f"{instance.id}_{attribute.id}", allow_unicode=True)
+ value, _created = update_or_create(
+ attribute=attribute,
+ slug=slug,
+ defaults=value_defaults,
+ )
+ return (value,)
+
@classmethod
def _pre_save_reference_values(
cls,
@@ -256,29 +300,6 @@ class AttributeAssignmentMixin:
if errors:
raise ValidationError(errors)
- @classmethod
- def _pre_save_rich_text_values(
- cls,
- instance: T_INSTANCE,
- attribute: attribute_models.Attribute,
- attr_values: AttrValuesInput,
- ):
- """Lazy-retrieve or create the database object from the supplied raw value."""
- value_model = attribute.values.model
- slug = slugify(f"{instance.id}_{attribute.id}", allow_unicode=True)
- value = value_model.objects.update_or_create(
- attribute=attribute,
- slug=slug,
- defaults={
- "rich_text": attr_values.rich_text,
- "name": truncatechars(
- clean_editor_js(attr_values.rich_text, to_string=True), 50
- ),
- },
- )[0]
-
- return (value,)
-
@classmethod
def clean_input(
cls,
@@ -398,20 +419,17 @@ class AttributeAssignmentMixin:
:param instance: the product or variant to associate the attribute against.
:param cleaned_input: the cleaned user input (refer to clean_attributes)
"""
+ pre_save_methods_mapping = {
+ AttributeInputType.FILE: cls._pre_save_file_value,
+ AttributeInputType.REFERENCE: cls._pre_save_reference_values,
+ AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,
+ AttributeInputType.NUMERIC: cls._pre_save_numeric_values,
+ }
clean_assignment = []
for attribute, attr_values in cleaned_input:
- if attribute.input_type == AttributeInputType.FILE:
- attribute_values = cls._pre_save_file_value(
- instance, attribute, attr_values
- )
- elif attribute.input_type == AttributeInputType.REFERENCE:
- attribute_values = cls._pre_save_reference_values(
- instance, attribute, attr_values
- )
- elif attribute.input_type == AttributeInputType.RICH_TEXT:
- attribute_values = cls._pre_save_rich_text_values(
- instance, attribute, attr_values
- )
+ if (input_type := attribute.input_type) in pre_save_methods_mapping:
+ pre_save_func = pre_save_methods_mapping[input_type]
+ attribute_values = pre_save_func(instance, attribute, attr_values)
else:
attribute_values = cls._pre_save_values(attribute, attr_values)
@@ -441,23 +459,26 @@ class AttributeInputErrors:
All used error codes must be specified in PageErrorCode and ProductErrorCode.
"""
- ERROR_NO_VALUE_GIVEN = ("Attribute expects a value but none were given", "REQUIRED")
- ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE = (
- "Attribute must take only one value",
+ ERROR_NO_VALUE_GIVEN = (
+ "Attribute expects a value but none were given.",
+ "REQUIRED",
+ )
+ ERROR_MORE_THAN_ONE_VALUE_GIVEN = (
+ "Attribute must take only one value.",
"INVALID",
)
ERROR_BLANK_VALUE = (
- "Attribute values cannot be blank",
+ "Attribute values cannot be blank.",
"REQUIRED",
)
# file errors
ERROR_NO_FILE_GIVEN = (
- "Attribute file url cannot be blank",
+ "Attribute file url cannot be blank.",
"REQUIRED",
)
ERROR_BLANK_FILE_VALUE = (
- "Attribute expects a file url but none were given",
+ "Attribute expects a file url but none were given.",
"REQUIRED",
)
@@ -467,6 +488,12 @@ class AttributeInputErrors:
"REQUIRED",
)
+ # numeric errors
+ ERROR_NUMERIC_VALUE_REQUIRED = (
+ "Numeric value is required.",
+ "INVALID",
+ )
+
# text errors
ERROR_MAX_LENGTH = (
"Attribute value length is exceeded.",
@@ -526,9 +553,7 @@ def validate_file_attributes_input(
attribute_id = attr_values.global_id
value = attr_values.file_url
if not value:
- if attribute.value_required or (
- variant_validation and is_variant_selection_attribute(attribute)
- ):
+ if is_value_required(attribute, variant_validation):
attribute_errors[AttributeInputErrors.ERROR_NO_FILE_GIVEN].append(
attribute_id
)
@@ -547,7 +572,7 @@ def validate_reference_attributes_input(
attribute_id = attr_values.global_id
references = attr_values.references
if not references:
- if attribute.value_required or variant_validation:
+ if is_value_required(attribute, variant_validation):
attribute_errors[AttributeInputErrors.ERROR_NO_REFERENCE_GIVEN].append(
attribute_id
)
@@ -573,12 +598,9 @@ def validate_standard_attributes_input(
variant_validation: bool,
):
attribute_id = attr_values.global_id
- name_field = attribute.values.model.name.field # type: ignore
if not attr_values.values:
- if attribute.value_required or (
- variant_validation and is_variant_selection_attribute(attribute)
- ):
+ if is_value_required(attribute, variant_validation):
attribute_errors[AttributeInputErrors.ERROR_NO_VALUE_GIVEN].append(
attribute_id
)
@@ -586,17 +608,46 @@ def validate_standard_attributes_input(
attribute.input_type != AttributeInputType.MULTISELECT
and len(attr_values.values) != 1
):
- attribute_errors[
- AttributeInputErrors.ERROR_DROPDOWN_GET_MORE_THAN_ONE_VALUE
- ].append(attribute_id)
+ attribute_errors[AttributeInputErrors.ERROR_MORE_THAN_ONE_VALUE_GIVEN].append(
+ attribute_id
+ )
- for value in attr_values.values:
- if value is None or not value.strip():
+ validate_values(
+ attribute_id,
+ attribute,
+ attr_values.values,
+ attribute_errors,
+ )
+
+
+def validate_values(
+ attribute_id: str,
+ attribute: "Attribute",
+ values: list,
+ attribute_errors: T_ERROR_DICT,
+):
+ name_field = attribute.values.model.name.field # type: ignore
+ is_numeric = attribute.input_type == AttributeInputType.NUMERIC
+ for value in values:
+ if value is None or (not is_numeric and not value.strip()):
attribute_errors[AttributeInputErrors.ERROR_BLANK_VALUE].append(
attribute_id
)
- elif len(value) > name_field.max_length:
+ elif not is_numeric and len(value) > name_field.max_length:
attribute_errors[AttributeInputErrors.ERROR_MAX_LENGTH].append(attribute_id)
+ elif is_numeric:
+ try:
+ float(value)
+ except ValueError:
+ attribute_errors[
+ AttributeInputErrors.ERROR_NUMERIC_VALUE_REQUIRED
+ ].append(attribute_id)
+
+
+def is_value_required(attribute: attribute_models.Attribute, variant_validation: bool):
+ return attribute.value_required or (
+ variant_validation and is_variant_selection_attribute(attribute)
+ )
def is_variant_selection_attribute(attribute: attribute_models.Attribute):
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index d0865c2e78..cd7ee83af4 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -9,7 +9,13 @@ from ...checkout import error_codes as checkout_error_codes
from ...core import JobStatus
from ...core import error_codes as core_error_codes
from ...core.permissions import get_permissions_enum_list
-from ...core.weight import WeightUnits
+from ...core.units import (
+ AreaUnits,
+ DistanceUnits,
+ MeasurementUnits,
+ VolumeUnits,
+ WeightUnits,
+)
from ...csv import error_codes as csv_error_codes
from ...discount import error_codes as discount_error_codes
from ...giftcard import error_codes as giftcard_error_codes
@@ -90,10 +96,14 @@ TaxRateType = graphene.Enum(
JobStatusEnum = to_enum(JobStatus)
PermissionEnum = graphene.Enum("PermissionEnum", get_permissions_enum_list())
-WeightUnitsEnum = graphene.Enum(
- "WeightUnitsEnum", [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES]
-)
+# unit enums
+MeasurementUnitsEnum = to_enum(MeasurementUnits)
+DistanceUnitsEnum = to_enum(DistanceUnits)
+AreaUnitsEnum = to_enum(AreaUnits)
+VolumeUnitsEnum = to_enum(VolumeUnits)
+WeightUnitsEnum = to_enum(WeightUnits)
+unit_enums = [DistanceUnitsEnum, AreaUnitsEnum, VolumeUnitsEnum, WeightUnitsEnum]
AccountErrorCode = graphene.Enum.from_enum(account_error_codes.AccountErrorCode)
AppErrorCode = graphene.Enum.from_enum(app_error_codes.AppErrorCode)
diff --git a/saleor/graphql/page/mutations/pages.py b/saleor/graphql/page/mutations/pages.py
index cead304bad..f961a4a11a 100644
--- a/saleor/graphql/page/mutations/pages.py
+++ b/saleor/graphql/page/mutations/pages.py
@@ -10,11 +10,11 @@ from ....attribute import AttributeType
from ....core.permissions import PagePermissions, PageTypePermissions
from ....page import models
from ....page.error_codes import PageErrorCode
+from ...attribute.types import AttributeValueInput
from ...attribute.utils import AttributeAssignmentMixin
from ...core.mutations import ModelDeleteMutation, ModelMutation
from ...core.types.common import PageError, SeoInput
from ...core.utils import clean_seo_fields, validate_slug_and_generate_if_needed
-from ...product.mutations.products import AttributeValueInput
from ...utils.validators import check_for_duplicates
if TYPE_CHECKING:
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index c7a41edb60..47e8851691 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -1,17 +1,20 @@
+import math
from collections import defaultdict
from typing import Dict, Iterable, List, Optional
import django_filters
import graphene
from django.contrib.postgres.search import SearchQuery, SearchRank
-from django.db.models import Exists, F, OuterRef, Q, Subquery, Sum
-from django.db.models.functions import Coalesce
+from django.db.models import Exists, F, FloatField, OuterRef, Q, Subquery, Sum
+from django.db.models.functions import Cast, Coalesce
from graphene_django.filter import GlobalIDMultipleChoiceFilter
+from ...attribute import AttributeInputType
from ...attribute.models import (
AssignedProductAttribute,
AssignedVariantAttribute,
Attribute,
+ AttributeValue,
)
from ...product.models import Category, Collection, Product, ProductType, ProductVariant
from ...warehouse.models import Stock
@@ -34,10 +37,10 @@ from .enums import (
StockAvailability,
)
+T_PRODUCT_FILTER_QUERIES = Dict[int, Iterable[int]]
+
-def _clean_product_attributes_filter_input(
- filter_value,
-) -> Dict[int, List[Optional[int]]]:
+def _clean_product_attributes_filter_input(filter_value, queries):
attributes = Attribute.objects.prefetch_related("values")
attributes_map: Dict[str, int] = {
attribute.slug: attribute.pk for attribute in attributes
@@ -46,7 +49,7 @@ def _clean_product_attributes_filter_input(
attr.slug: {value.slug: value.pk for value in attr.values.all()}
for attr in attributes
}
- queries: Dict[int, List[Optional[int]]] = defaultdict(list)
+
# Convert attribute:value pairs into a dictionary where
# attributes are keys and values are grouped in lists
for attr_name, val_slugs in filter_value:
@@ -60,10 +63,34 @@ def _clean_product_attributes_filter_input(
]
queries[attr_pk] += attr_val_pk
- return queries
+def _clean_product_attributes_range_filter_input(filter_value, queries):
+ values = (
+ AttributeValue.objects.filter(attribute__input_type=AttributeInputType.NUMERIC)
+ .annotate(numeric_value=Cast("name", FloatField()))
+ .select_related("attribute")
+ )
-T_PRODUCT_FILTER_QUERIES = Dict[int, Iterable[int]]
+ attributes_map: Dict[str, int] = {}
+ values_map: Dict[str, Dict[str, int]] = defaultdict(dict)
+ for value_data in values.values_list(
+ "attribute_id", "attribute__slug", "pk", "numeric_value"
+ ):
+ attr_pk, attr_slug, pk, numeric_value = value_data
+ attributes_map[attr_slug] = attr_pk
+ values_map[attr_slug][numeric_value] = pk
+
+ for attr_name, val_range in filter_value:
+ if attr_name not in attributes_map:
+ raise ValueError("Unknown numeric attribute name: %r" % (attr_name,))
+ gte, lte = val_range.get("gte", 0), val_range.get("lte", math.inf)
+ attr_pk = attributes_map[attr_name]
+ attr_values = values_map[attr_name]
+ matching_values = [
+ value for value in attr_values.keys() if gte <= value and lte >= value
+ ]
+ attr_val_pks = [attr_values[value] for value in matching_values]
+ queries[attr_pk] += attr_val_pks
def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):
@@ -88,9 +115,13 @@ def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):
return qs.filter(*filters)
-def filter_products_by_attributes(qs, filter_value):
+def filter_products_by_attributes(qs, filter_values, filter_range_values):
+ queries: Dict[int, List[Optional[int]]] = defaultdict(list)
try:
- queries = _clean_product_attributes_filter_input(filter_value)
+ if filter_values:
+ _clean_product_attributes_filter_input(filter_values, queries)
+ if filter_range_values:
+ _clean_product_attributes_range_filter_input(filter_range_values, queries)
except ValueError:
return Product.objects.none()
return filter_products_by_attributes_values(qs, queries)
@@ -167,11 +198,14 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
def _filter_attributes(qs, _, value):
if value:
value_list = []
+ value_range_list = []
for v in value:
slug = v["slug"]
- values = [v["value"]] if "value" in v else v.get("values", [])
- value_list.append((slug, values))
- qs = filter_products_by_attributes(qs, value_list)
+ if "values" in v:
+ value_list.append((slug, v["values"]))
+ elif "values_range" in v:
+ value_range_list.append((slug, v["values_range"]))
+ qs = filter_products_by_attributes(qs, value_list, value_range_list)
return qs
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 19250fc4d4..7a323721a3 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -6,7 +6,6 @@ import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from django.utils.text import slugify
-from graphene.types import InputObjectType
from ....attribute import AttributeInputType, AttributeType
from ....attribute import models as attribute_models
@@ -31,6 +30,7 @@ from ....product.thumbnails import (
)
from ....product.utils import delete_categories, get_products_ids_without_variants
from ....product.utils.variants import generate_and_set_variant_name
+from ...attribute.types import AttributeValueInput
from ...attribute.utils import AttributeAssignmentMixin, AttrValuesInput
from ...channel import ChannelContext
from ...core.inputs import ReorderInput
@@ -485,31 +485,6 @@ class CollectionRemoveProducts(BaseMutation):
)
-class AttributeValueInput(InputObjectType):
- id = graphene.ID(description="ID of the selected attribute.")
- values = graphene.List(
- graphene.String,
- required=False,
- description=(
- "The value or slug of an attribute to resolve. "
- "If the passed value is non-existent, it will be created."
- ),
- )
- file = graphene.String(
- required=False,
- description="URL of the file attribute. Every time, a new value is created.",
- )
- content_type = graphene.String(required=False, description="File content type.")
- references = graphene.List(
- graphene.NonNull(graphene.ID),
- description="List of entity IDs that will be used as references.",
- required=False,
- )
- rich_text = graphene.JSONString(
- required=False, description="Text content in JSON format."
- )
-
-
class ProductInput(graphene.InputObjectType):
attributes = graphene.List(
graphene.NonNull(AttributeValueInput), description="List of attributes."
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index db36529f84..8e803f4219 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -4,6 +4,7 @@ import graphene
import pytest
from graphene import Node
+from .....attribute.utils import associate_attribute_values_to_instance
from .....core.taxes import TaxType
from .....plugins.manager import PluginsManager
from ....tests.utils import get_graphql_content
@@ -348,8 +349,6 @@ def test_retrive_products_with_product_types_and_attributes(
get_graphql_content(api_client.post_graphql(query, variables))
[email protected]_queries(autouse=False)
def test_product_create(
settings,
staff_api_client,
@@ -456,8 +455,6 @@ def test_product_create(
assert not content["data"]["productCreate"]["errors"]
[email protected]_queries(autouse=False)
def test_update_product(
settings,
staff_api_client,
@@ -555,3 +552,81 @@ def test_update_product(
content = get_graphql_content(response)
data = content["data"]["productUpdate"]
assert not data["errors"]
+
+
[email protected]_queries(autouse=False)
+def test_filter_products_by_attributes(
+ api_client, product_list, channel_USD, count_queries
+):
+ query = """
+ query ($channel: String, $filter: ProductFilterInput){
+ products(
+ channel: $channel,
+ filter: $filter,
+ first: 20,
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+
+ product = product_list[0]
+ attr_assignment = product.attributes.first()
+ attr = attr_assignment.attribute
+ variables = {
+ "channel": channel_USD.slug,
+ "filter": {
+ "attributes": [
+ {"slug": attr.slug, "values": [attr_assignment.values.first().slug]}
+ ]
+ },
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
[email protected]_queries(autouse=False)
+def test_filter_products_by_numeric_attributes(
+ api_client, product_list, numeric_attribute, channel_USD, count_queries
+):
+ query = """
+ query ($channel: String, $filter: ProductFilterInput){
+ products(
+ channel: $channel,
+ filter: $filter,
+ first: 20,
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+
+ product = product_list[0]
+ product.product_type.product_attributes.add(numeric_attribute)
+ associate_attribute_values_to_instance(
+ product, numeric_attribute, *numeric_attribute.values.all()
+ )
+ variables = {
+ "channel": channel_USD.slug,
+ "filter": {
+ "attributes": [
+ {
+ "slug": numeric_attribute.slug,
+ "valuesRange": {
+ "gte": 10,
+ "lte": 20,
+ },
+ }
+ ]
+ },
+ }
+ get_graphql_content(api_client.post_graphql(query, variables))
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 7c4ecf8b4a..e60d32d6e2 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -18,7 +18,7 @@ from ....attribute import AttributeInputType, AttributeType
from ....attribute.models import Attribute, AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
from ....core.taxes import TaxType
-from ....core.weight import WeightUnits
+from ....core.units import WeightUnits
from ....order import OrderStatus
from ....order.models import OrderLine
from ....plugins.manager import PluginsManager
@@ -623,7 +623,7 @@ def test_product_query_by_id_weight_returned_in_default_unit(
product.weight = Weight(kg=10)
product.save(update_fields=["weight"])
- site_settings.default_weight_unit = WeightUnits.POUND
+ site_settings.default_weight_unit = WeightUnits.LB
site_settings.save(update_fields=["default_weight_unit"])
variables = {
@@ -640,7 +640,7 @@ def test_product_query_by_id_weight_returned_in_default_unit(
assert product_data is not None
assert product_data["name"] == product.name
assert product_data["weight"]["value"] == 22.046
- assert product_data["weight"]["unit"] == WeightUnits.POUND.upper()
+ assert product_data["weight"]["unit"] == WeightUnits.LB.upper()
def test_product_query_by_id_weight_is_rounded(
@@ -650,7 +650,7 @@ def test_product_query_by_id_weight_is_rounded(
product.weight = Weight(kg=1.83456)
product.save(update_fields=["weight"])
- site_settings.default_weight_unit = WeightUnits.KILOGRAM
+ site_settings.default_weight_unit = WeightUnits.KG
site_settings.save(update_fields=["default_weight_unit"])
variables = {
@@ -667,7 +667,7 @@ def test_product_query_by_id_weight_is_rounded(
assert product_data is not None
assert product_data["name"] == product.name
assert product_data["weight"]["value"] == 1.835
- assert product_data["weight"]["unit"] == WeightUnits.KILOGRAM.upper()
+ assert product_data["weight"]["unit"] == WeightUnits.KG.upper()
def test_product_query_by_slug(user_api_client, product, channel_USD):
@@ -1655,6 +1655,149 @@ def test_products_query_with_filter_attributes(
assert products[0]["node"]["name"] == second_product.name
+ "gte, lte, expected_products",
+ [
+ (None, 8, [1]),
+ (0, 8, [1]),
+ (7, 8, []),
+ (5, None, [0, 1]),
+ (8, 10, [0]),
+ (12, None, [0]),
+ (20, None, []),
+ (20, 8, []),
+ ],
+)
+def test_products_query_with_filter_numeric_attributes(
+ gte,
+ lte,
+ expected_products,
+ query_products_with_filter,
+ staff_api_client,
+ product,
+ category,
+ numeric_attribute,
+ permission_manage_products,
+):
+ product.product_type.product_attributes.add(numeric_attribute)
+ associate_attribute_values_to_instance(
+ product, numeric_attribute, *numeric_attribute.values.all()
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ numeric_attribute.product_types.add(product_type)
+
+ second_product = Product.objects.create(
+ name="Second product",
+ slug="second-product",
+ product_type=product_type,
+ category=category,
+ )
+ attr_value = AttributeValue.objects.create(
+ attribute=numeric_attribute, name="5.2", slug="5_2"
+ )
+
+ associate_attribute_values_to_instance(
+ second_product, numeric_attribute, attr_value
+ )
+
+ second_product.refresh_from_db()
+ products_instances = [product, second_product]
+ products_ids = [
+ graphene.Node.to_global_id("Product", p.pk) for p in products_instances
+ ]
+ values_range = {}
+ if gte:
+ values_range["gte"] = gte
+ if lte:
+ values_range["lte"] = lte
+ variables = {
+ "filter": {
+ "attributes": [
+ {"slug": numeric_attribute.slug, "valuesRange": values_range}
+ ]
+ }
+ }
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(query_products_with_filter, variables)
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == len(expected_products)
+ assert set(product["node"]["id"] for product in products) == {
+ products_ids[index] for index in expected_products
+ }
+ assert set(product["node"]["name"] for product in products) == {
+ products_instances[index].name for index in expected_products
+ }
+
+
+def test_products_query_with_filter_by_attributes_values_and_range(
+ query_products_with_filter,
+ staff_api_client,
+ product,
+ category,
+ numeric_attribute,
+ permission_manage_products,
+):
+ product_attr = product.attributes.first()
+ attr_value_1 = product_attr.values.first()
+ product.product_type.product_attributes.add(numeric_attribute)
+ associate_attribute_values_to_instance(
+ product, numeric_attribute, *numeric_attribute.values.all()
+ )
+
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ numeric_attribute.product_types.add(product_type)
+
+ second_product = Product.objects.create(
+ name="Second product",
+ slug="second-product",
+ product_type=product_type,
+ category=category,
+ )
+ attr_value_2 = AttributeValue.objects.create(
+ attribute=numeric_attribute, name="5.2", slug="5_2"
+ )
+
+ associate_attribute_values_to_instance(
+ second_product, numeric_attribute, attr_value_2
+ )
+
+ second_product.refresh_from_db()
+
+ variables = {
+ "filter": {
+ "attributes": [
+ {"slug": numeric_attribute.slug, "valuesRange": {"gte": 2}},
+ {"slug": attr_value_1.attribute.slug, "values": [attr_value_1.slug]},
+ ]
+ }
+ }
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(query_products_with_filter, variables)
+ content = get_graphql_content(response)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == graphene.Node.to_global_id(
+ "Product", product.pk
+ )
+ assert products[0]["node"]["name"] == product.name
+
+
def test_products_query_filter_by_non_existing_attribute(
query_products_with_filter, api_client, product_list, channel_USD
):
@@ -2339,16 +2482,11 @@ def test_get_product_with_sorted_attribute_values(
def test_filter_products_by_wrong_attributes(user_api_client, product, channel_USD):
product_attr = product.product_type.product_attributes.get(slug="color")
- attr_value = (
- product.product_type.variant_attributes.get(slug="size").values.first().id
- )
+ attr_value = product.product_type.variant_attributes.get(slug="size").values.first()
query = """
- query ($channel: String, $attributesFilter: [AttributeInput]){
+ query ($channel: String, $filter: ProductFilterInput){
products(
- filter: {
- attributes: $attributesFilter,
- channel: $channel
- },
+ filter: $filter,
first: 1,
channel: $channel
) {
@@ -2363,7 +2501,9 @@ def test_filter_products_by_wrong_attributes(user_api_client, product, channel_U
variables = {
"channel": channel_USD.slug,
- "attributesFilter": [{"slug": product_attr.slug, "values": [attr_value]}],
+ "filter": {
+ "attributes": [{"slug": product_attr.slug, "values": [attr_value.slug]}]
+ },
}
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -2718,7 +2858,7 @@ def test_product_type_query_by_id_weight_returned_in_default_unit(
product_type.weight = Weight(kg=10)
product_type.save(update_fields=["weight"])
- site_settings.default_weight_unit = WeightUnits.OUNCE
+ site_settings.default_weight_unit = WeightUnits.OZ
site_settings.save(update_fields=["default_weight_unit"])
variables = {"id": graphene.Node.to_global_id("ProductType", product_type.pk)}
@@ -2732,7 +2872,7 @@ def test_product_type_query_by_id_weight_returned_in_default_unit(
assert product_data is not None
assert product_data["name"] == product_type.name
assert product_data["weight"]["value"] == 352.73999999999995
- assert product_data["weight"]["unit"] == WeightUnits.OUNCE.upper()
+ assert product_data["weight"]["unit"] == WeightUnits.OZ.upper()
CREATE_PRODUCT_MUTATION = """
@@ -3768,6 +3908,169 @@ def test_create_product_no_values_given(
assert data["product"]["attributes"][0]["values"] == []
+ "value, expected_name, expected_slug",
+ [(20.1, "20.1", "20_1"), (20, "20", "20"), ("1", "1", "1")],
+)
+def test_create_product_with_numeric_attribute_new_attribute_value(
+ value,
+ expected_name,
+ expected_slug,
+ staff_api_client,
+ product_type,
+ category,
+ numeric_attribute,
+ permission_manage_products,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+
+ values_count = numeric_attribute.values.count()
+
+ # Add second attribute
+ product_type.product_attributes.set([numeric_attribute])
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": attr_id, "values": [value]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ product_pk = graphene.Node.from_global_id(data["product"]["id"])[1]
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ assert data["product"]["productType"]["name"] == product_type.name
+ assert data["product"]["category"]["name"] == category.name
+ assert len(data["product"]["attributes"]) == 1
+ assert (
+ data["product"]["attributes"][0]["attribute"]["slug"] == numeric_attribute.slug
+ )
+ values = data["product"]["attributes"][0]["values"]
+ assert len(values) == 1
+ assert values[0]["name"] == expected_name
+ assert values[0]["slug"] == f"{product_pk}_{numeric_attribute.id}"
+
+ numeric_attribute.refresh_from_db()
+ assert numeric_attribute.values.count() == values_count + 1
+
+
+def test_create_product_with_numeric_attribute_existing_value(
+ staff_api_client,
+ product_type,
+ category,
+ numeric_attribute,
+ permission_manage_products,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+
+ values_count = numeric_attribute.values.count()
+
+ # Add second attribute
+ product_type.product_attributes.set([numeric_attribute])
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)
+ existing_value = numeric_attribute.values.first()
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": attr_id, "values": [existing_value.name]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ product_pk = graphene.Node.from_global_id(data["product"]["id"])[1]
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ assert data["product"]["productType"]["name"] == product_type.name
+ assert data["product"]["category"]["name"] == category.name
+ assert len(data["product"]["attributes"]) == 1
+ assert (
+ data["product"]["attributes"][0]["attribute"]["slug"] == numeric_attribute.slug
+ )
+ values = data["product"]["attributes"][0]["values"]
+ assert len(values) == 1
+ assert values[0]["name"] == existing_value.name
+ assert values[0]["slug"] == f"{product_pk}_{numeric_attribute.id}"
+
+ numeric_attribute.refresh_from_db()
+ assert numeric_attribute.values.count() == values_count + 1
+
+
+def test_create_product_with_numeric_attribute_not_numeric_value_given(
+ staff_api_client,
+ product_type,
+ category,
+ numeric_attribute,
+ permission_manage_products,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+
+ values_count = numeric_attribute.values.count()
+
+ # Add second attribute
+ product_type.product_attributes.set([numeric_attribute])
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.id)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": attr_id, "values": ["abd"]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert not data["product"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "attributes"
+ assert data["errors"][0]["code"] == AttributeErrorCode.INVALID.name
+
+ numeric_attribute.refresh_from_db()
+ assert numeric_attribute.values.count() == values_count
+
+
PRODUCT_VARIANT_SET_DEFAULT_MUTATION = """
mutation Prod($productId: ID!, $variantId: ID!) {
productVariantSetDefault(productId: $productId, variantId: $variantId) {
@@ -4676,6 +4979,123 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(
updated_webhook_mock.assert_called_once_with(product)
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_numeric_attribute_value(
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ numeric_attribute,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ product_type.product_attributes.add(numeric_attribute)
+
+ new_value = "45.2"
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "values": [new_value]}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert data["errors"] == []
+
+ attributes = data["product"]["attributes"]
+ assert len(attributes) == 2
+ expected_att_data = {
+ "attribute": {"id": attribute_id, "name": numeric_attribute.name},
+ "values": [
+ {
+ "id": ANY,
+ "name": new_value,
+ "slug": slugify(
+ f"{product.id}_{numeric_attribute.id}", allow_unicode=True
+ ),
+ "reference": None,
+ "file": None,
+ }
+ ],
+ }
+ assert expected_att_data in attributes
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_numeric_attribute_value_new_value_is_not_created(
+ updated_webhook_mock,
+ staff_api_client,
+ numeric_attribute,
+ product,
+ product_type,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ product_type.product_attributes.add(numeric_attribute)
+ slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
+ value = AttributeValue.objects.create(
+ attribute=numeric_attribute, slug=slug_value, name="20.0"
+ )
+ associate_attribute_values_to_instance(product, numeric_attribute, value)
+
+ value_count = AttributeValue.objects.count()
+
+ new_value = "45.2"
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "values": [new_value]}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert data["errors"] == []
+
+ attributes = data["product"]["attributes"]
+
+ assert len(attributes) == 2
+ expected_att_data = {
+ "attribute": {"id": attribute_id, "name": numeric_attribute.name},
+ "values": [
+ {
+ "id": ANY,
+ "name": new_value,
+ "slug": slug_value,
+ "reference": None,
+ "file": None,
+ }
+ ],
+ }
+ assert expected_att_data in attributes
+
+ assert AttributeValue.objects.count() == value_count
+ value.refresh_from_db()
+ assert value.name == new_value
+
+
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_update_product_clear_attribute_values(
updated_webhook_mock,
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 1396fe0133..937c3e42c5 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -11,7 +11,7 @@ from prices import Money, TaxedMoney
from ....attribute import AttributeInputType
from ....attribute.models import AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
-from ....core.weight import WeightUnits
+from ....core.units import WeightUnits
from ....order import OrderStatus
from ....order.models import OrderLine
from ....product.error_codes import ProductErrorCode
@@ -95,7 +95,7 @@ def test_fetch_variant(
variant.weight = Weight(kg=10)
variant.save(update_fields=["weight"])
- site_settings.default_weight_unit = WeightUnits.GRAM
+ site_settings.default_weight_unit = WeightUnits.G
site_settings.save(update_fields=["default_weight_unit"])
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
@@ -731,6 +731,9 @@ def test_create_variant_with_page_reference_attribute_no_references_given(
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
+ product_type_page_reference_attribute.value_required = True
+ product_type_page_reference_attribute.save(update_fields=["value_required"])
+
product_type.variant_attributes.clear()
product_type.variant_attributes.add(product_type_page_reference_attribute)
ref_attr_id = graphene.Node.to_global_id(
@@ -789,6 +792,9 @@ def test_create_variant_with_product_reference_attribute(
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
+ product_type_product_reference_attribute.value_required = True
+ product_type_product_reference_attribute.save(update_fields=["value_required"])
+
product_type.variant_attributes.clear()
product_type.variant_attributes.add(product_type_product_reference_attribute)
ref_attr_id = graphene.Node.to_global_id(
@@ -875,6 +881,9 @@ def test_create_variant_with_product_reference_attribute_no_references_given(
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
+ product_type_product_reference_attribute.value_required = True
+ product_type_product_reference_attribute.save(update_fields=["value_required"])
+
product_type.variant_attributes.clear()
product_type.variant_attributes.add(product_type_product_reference_attribute)
ref_attr_id = graphene.Node.to_global_id(
@@ -918,6 +927,106 @@ def test_create_variant_with_product_reference_attribute_no_references_given(
updated_webhook_mock.assert_not_called()
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+def test_create_variant_with_numeric_attribute(
+ created_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+ warehouse,
+ numeric_attribute,
+):
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+ weight = 10.22
+ product_type.variant_attributes.set([numeric_attribute])
+ variant_slug = numeric_attribute.slug
+ variant_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ variant_value = "22.31"
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "productId": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "weight": weight,
+ "attributes": [{"id": variant_id, "values": [variant_value]}],
+ "trackInventory": True,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ assert not content["errors"]
+ data = content["productVariant"]
+ variant_pk = graphene.Node.from_global_id(data["id"])[1]
+ assert data["name"] == sku
+ assert data["sku"] == sku
+ assert data["attributes"][0]["attribute"]["slug"] == variant_slug
+ assert (
+ data["attributes"][0]["values"][0]["slug"]
+ == f"{variant_pk}_{numeric_attribute.pk}"
+ )
+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name
+ assert data["weight"]["value"] == weight
+ assert len(data["stocks"]) == 1
+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+ created_webhook_mock.assert_called_once_with(product.variants.last())
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_create_variant_with_numeric_attribute_not_numeric_value_given(
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+ warehouse,
+ numeric_attribute,
+):
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+ weight = 10.22
+ product_type.variant_attributes.set([numeric_attribute])
+ variant_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ variant_value = "abd"
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "productId": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "weight": weight,
+ "attributes": [{"id": variant_id, "values": [variant_value]}],
+ "trackInventory": True,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantCreate"]
+ error = data["errors"][0]
+ assert not data["productVariant"]
+ assert error["field"] == "attributes"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+ updated_webhook_mock.assert_not_called()
+
+
def test_create_product_variant_with_negative_weight(
staff_api_client, product, product_type, permission_manage_products
):
@@ -2006,10 +2115,10 @@ def test_update_product_variant_change_attribute_values_ordering(
@pytest.mark.parametrize(
"values, message, code",
(
- ([], "Attribute expects a value but none were given", "REQUIRED"),
- (["one", "two"], "Attribute must take only one value", "INVALID"),
- ([" "], "Attribute values cannot be blank", "REQUIRED"),
- ([None], "Attribute values cannot be blank", "REQUIRED"),
+ ([], "Attribute expects a value but none were given.", "REQUIRED"),
+ (["one", "two"], "Attribute must take only one value.", "INVALID"),
+ ([" "], "Attribute values cannot be blank.", "REQUIRED"),
+ ([None], "Attribute values cannot be blank.", "REQUIRED"),
),
)
def test_update_product_variant_requires_values(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 537d15587a..c131e6a921 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -382,6 +382,15 @@ type AppUpdate {
app: App
}
+enum AreaUnitsEnum {
+ SQ_CM
+ SQ_M
+ SQ_KM
+ SQ_FT
+ SQ_YD
+ SQ_INCH
+}
+
type AssignNavigation {
menu: Menu
menuErrors: [MenuError!]! @deprecated(reason: "Use errors field instead. This field will be removed in Saleor 4.0.")
@@ -399,6 +408,7 @@ type Attribute implements Node & ObjectWithMetadata {
name: String
slug: String
type: AttributeTypeEnum
+ unit: MeasurementUnitsEnum
values: [AttributeValue]
valueRequired: Boolean!
visibleInStorefront: Boolean!
@@ -438,6 +448,7 @@ input AttributeCreateInput {
name: String!
slug: String
type: AttributeTypeEnum!
+ unit: MeasurementUnitsEnum
values: [AttributeValueCreateInput]
valueRequired: Boolean
isVariantOnly: Boolean
@@ -493,6 +504,7 @@ input AttributeFilterInput {
input AttributeInput {
slug: String!
values: [String]
+ valuesRange: IntRangeInput
}
enum AttributeInputTypeEnum {
@@ -500,6 +512,7 @@ enum AttributeInputTypeEnum {
MULTISELECT
FILE
REFERENCE
+ NUMERIC
RICH_TEXT
}
@@ -559,6 +572,7 @@ type AttributeUpdate {
input AttributeUpdateInput {
name: String
slug: String
+ unit: MeasurementUnitsEnum
removeValues: [ID]
addValues: [AttributeValueCreateInput]
valueRequired: Boolean
@@ -1781,6 +1795,15 @@ enum DiscountValueTypeEnum {
PERCENTAGE
}
+enum DistanceUnitsEnum {
+ CM
+ M
+ KM
+ FT
+ YD
+ INCH
+}
+
type Domain {
host: String!
sslEnabled: Boolean!
@@ -2367,6 +2390,39 @@ type Margin {
stop: Int
}
+enum MeasurementUnitsEnum {
+ CM
+ M
+ KM
+ FT
+ YD
+ INCH
+ SQ_CM
+ SQ_M
+ SQ_KM
+ SQ_FT
+ SQ_YD
+ SQ_INCH
+ CUBIC_MILLIMETER
+ CUBIC_CENTIMETER
+ CUBIC_DECIMETER
+ CUBIC_METER
+ LITER
+ CUBIC_FOOT
+ CUBIC_INCH
+ CUBIC_YARD
+ QT
+ PINT
+ FL_OZ
+ ACRE_IN
+ ACRE_FT
+ G
+ LB
+ OZ
+ KG
+ TONNE
+}
+
type Menu implements Node & ObjectWithMetadata {
id: ID!
name: String!
@@ -5636,6 +5692,22 @@ type VerifyToken {
errors: [AccountError!]!
}
+enum VolumeUnitsEnum {
+ CUBIC_MILLIMETER
+ CUBIC_CENTIMETER
+ CUBIC_DECIMETER
+ CUBIC_METER
+ LITER
+ CUBIC_FOOT
+ CUBIC_INCH
+ CUBIC_YARD
+ QT
+ PINT
+ FL_OZ
+ ACRE_IN
+ ACRE_FT
+}
+
type Voucher implements Node {
id: ID!
name: String
@@ -6042,10 +6114,11 @@ type Weight {
scalar WeightScalar
enum WeightUnitsEnum {
- KG
+ G
LB
OZ
- G
+ KG
+ TONNE
}
scalar _Any
diff --git a/saleor/graphql/shipping/tests/test_shipping_zones_query.py b/saleor/graphql/shipping/tests/test_shipping_zones_query.py
index ed61310ae7..0735135cf5 100644
--- a/saleor/graphql/shipping/tests/test_shipping_zones_query.py
+++ b/saleor/graphql/shipping/tests/test_shipping_zones_query.py
@@ -2,7 +2,7 @@ import graphene
import pytest
from measurement.measures import Weight
-from ....core.weight import WeightUnits
+from ....core.units import WeightUnits
from ...shipping.resolvers import resolve_price_range
from ...tests.utils import get_graphql_content
@@ -94,7 +94,7 @@ def test_shipping_zone_query_weights_returned_in_default_unit(
shipping_method.maximum_order_weight = Weight(kg=10)
shipping_method.save(update_fields=["minimum_order_weight", "maximum_order_weight"])
- site_settings.default_weight_unit = WeightUnits.GRAM
+ site_settings.default_weight_unit = WeightUnits.G
site_settings.save(update_fields=["default_weight_unit"])
query = SHIPPING_ZONE_QUERY
@@ -120,12 +120,12 @@ def test_shipping_zone_query_weights_returned_in_default_unit(
assert shipping_data["shippingMethods"][0]["minimumOrderWeight"]["value"] == 1000
assert (
shipping_data["shippingMethods"][0]["minimumOrderWeight"]["unit"]
- == WeightUnits.GRAM.upper()
+ == WeightUnits.G.upper()
)
assert shipping_data["shippingMethods"][0]["maximumOrderWeight"]["value"] == 10000
assert (
shipping_data["shippingMethods"][0]["maximumOrderWeight"]["unit"]
- == WeightUnits.GRAM.upper()
+ == WeightUnits.G.upper()
)
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 8df6d78cb4..8e138ee027 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -20,8 +20,9 @@ from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.permissions import OrderPermissions
from ..core.taxes import zero_taxed_money
+from ..core.units import WeightUnits
from ..core.utils.json_serializer import CustomJsonEncoder
-from ..core.weight import WeightUnits, zero_weight
+from ..core.weight import zero_weight
from ..discount import DiscountValueType
from ..discount.models import Voucher
from ..giftcard.models import GiftCard
@@ -210,7 +211,9 @@ class Order(ModelWithMetadata):
display_gross_prices = models.BooleanField(default=True)
customer_note = models.TextField(blank=True, default="")
weight = MeasurementField(
- measurement=Weight, unit_choices=WeightUnits.CHOICES, default=zero_weight
+ measurement=Weight,
+ unit_choices=WeightUnits.CHOICES, # type: ignore
+ default=zero_weight,
)
redirect_url = models.URLField(blank=True, null=True)
objects = OrderQueryset.as_manager()
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 57850b08f9..3198994dcf 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -39,11 +39,12 @@ from ..channel.models import Channel
from ..core.db.fields import SanitizedJSONField
from ..core.models import ModelWithMetadata, PublishableModel, SortableModel
from ..core.permissions import ProductPermissions, ProductTypePermissions
+from ..core.units import WeightUnits
from ..core.utils import build_absolute_uri
from ..core.utils.draftjs import json_content_to_raw_text
from ..core.utils.editorjs import clean_editor_js
from ..core.utils.translations import TranslationProxy
-from ..core.weight import WeightUnits, zero_weight
+from ..core.weight import zero_weight
from ..discount import DiscountInfo
from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel, SeoModelTranslation
@@ -109,7 +110,9 @@ class ProductType(ModelWithMetadata):
is_shipping_required = models.BooleanField(default=True)
is_digital = models.BooleanField(default=False)
weight = MeasurementField(
- measurement=Weight, unit_choices=WeightUnits.CHOICES, default=zero_weight
+ measurement=Weight,
+ unit_choices=WeightUnits.CHOICES, # type: ignore
+ default=zero_weight,
)
class Meta(ModelWithMetadata.Meta):
@@ -338,7 +341,10 @@ class Product(SeoModel, ModelWithMetadata):
updated_at = models.DateTimeField(auto_now=True, null=True)
charge_taxes = models.BooleanField(default=True)
weight = MeasurementField(
- measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
+ measurement=Weight,
+ unit_choices=WeightUnits.CHOICES, # type: ignore
+ blank=True,
+ null=True,
)
default_variant = models.OneToOneField(
"ProductVariant",
@@ -488,7 +494,10 @@ class ProductVariant(SortableModel, ModelWithMetadata):
track_inventory = models.BooleanField(default=True)
weight = MeasurementField(
- measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
+ measurement=Weight,
+ unit_choices=WeightUnits.CHOICES, # type: ignore
+ blank=True,
+ null=True,
)
objects = ProductVariantQueryset.as_manager()
diff --git a/saleor/product/tests/test_get_variant_selection_attributes.py b/saleor/product/tests/test_get_variant_selection_attributes.py
index 5d40728eff..2f078ef212 100644
--- a/saleor/product/tests/test_get_variant_selection_attributes.py
+++ b/saleor/product/tests/test_get_variant_selection_attributes.py
@@ -4,6 +4,7 @@ from ..utils.variants import get_variant_selection_attributes
def test_get_variant_selection_attributes(
product_type_attribute_list,
+ numeric_attribute,
file_attribute_with_file_input_type_without_values,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
@@ -14,6 +15,7 @@ def test_get_variant_selection_attributes(
multiselect_attr.save(update_fields=["input_type"])
attrs = product_type_attribute_list + [
+ numeric_attribute,
file_attribute_with_file_input_type_without_values,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 0679c6ef96..8acedb90d1 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -13,14 +13,10 @@ from ..channel.models import Channel
from ..core.db.fields import SanitizedJSONField
from ..core.models import ModelWithMetadata
from ..core.permissions import ShippingPermissions
+from ..core.units import WeightUnits
from ..core.utils.editorjs import clean_editor_js
from ..core.utils.translations import TranslationProxy
-from ..core.weight import (
- WeightUnits,
- convert_weight,
- get_default_weight_unit,
- zero_weight,
-)
+from ..core.weight import convert_weight, get_default_weight_unit, zero_weight
from . import PostalCodeRuleInclusionType, ShippingMethodType
from .postal_codes import filter_shipping_methods_by_postal_code_rules
@@ -190,13 +186,16 @@ class ShippingMethod(ModelWithMetadata):
)
minimum_order_weight = MeasurementField(
measurement=Weight,
- unit_choices=WeightUnits.CHOICES,
+ unit_choices=WeightUnits.CHOICES, # type: ignore
default=zero_weight,
blank=True,
null=True,
)
maximum_order_weight = MeasurementField(
- measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
+ measurement=Weight,
+ unit_choices=WeightUnits.CHOICES, # type: ignore
+ blank=True,
+ null=True,
)
excluded_products = models.ManyToManyField(
"product.Product", blank=True
diff --git a/saleor/site/migrations/0029_auto_20210120_0934.py b/saleor/site/migrations/0029_auto_20210120_0934.py
new file mode 100644
index 0000000000..54719dfaba
--- /dev/null
+++ b/saleor/site/migrations/0029_auto_20210120_0934.py
@@ -0,0 +1,28 @@
+# Generated by Django 3.1.4 on 2021-01-20 09:34
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("site", "0028_delete_authorizationkey"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="sitesettings",
+ name="default_weight_unit",
+ field=models.CharField(
+ choices=[
+ ("g", "Gram"),
+ ("lb", "Pound"),
+ ("oz", "Ounce"),
+ ("kg", "kg"),
+ ("tonne", "Tonne"),
+ ],
+ default="kg",
+ max_length=30,
+ ),
+ ),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index d27ed43ae5..9b93fe4e3f 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -9,8 +9,8 @@ from django.core.validators import MaxLengthValidator, RegexValidator
from django.db import models
from ..core.permissions import SitePermissions
+from ..core.units import WeightUnits
from ..core.utils.translations import TranslationProxy
-from ..core.weight import WeightUnits
from .error_codes import SiteErrorCode
from .patch_sites import patch_contrib_sites
@@ -44,7 +44,9 @@ class SiteSettings(models.Model):
charge_taxes_on_shipping = models.BooleanField(default=True)
track_inventory_by_default = models.BooleanField(default=True)
default_weight_unit = models.CharField(
- max_length=10, choices=WeightUnits.CHOICES, default=WeightUnits.KILOGRAM
+ max_length=30,
+ choices=WeightUnits.CHOICES, # type: ignore
+ default=WeightUnits.KG, # type: ignore
)
automatic_fulfillment_digital_products = models.BooleanField(default=False)
default_digital_max_downloads = models.IntegerField(blank=True, null=True)
diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.json
index d02dd1f193..424c6f2bda 100644
--- a/saleor/static/populatedb_data.json
+++ b/saleor/static/populatedb_data.json
@@ -8436,6 +8436,50 @@
]
}
},
+ {
+ "model": "attribute.assignedvariantattribute",
+ "pk": 127,
+ "fields": {
+ "variant": 198,
+ "assignment": 9,
+ "values": [
+ 97
+ ]
+ }
+ },
+ {
+ "model": "attribute.assignedvariantattribute",
+ "pk": 128,
+ "fields": {
+ "variant": 198,
+ "assignment": 10,
+ "values": [
+ 98
+ ]
+ }
+ },
+ {
+ "model": "attribute.assignedvariantattribute",
+ "pk": 129,
+ "fields": {
+ "variant": 197,
+ "assignment": 9,
+ "values": [
+ 100
+ ]
+ }
+ },
+ {
+ "model": "attribute.assignedvariantattribute",
+ "pk": 130,
+ "fields": {
+ "variant": 197,
+ "assignment": 10,
+ "values": [
+ 99
+ ]
+ }
+ },
{
"model": "attribute.assignedpageattribute",
"pk": 1,
@@ -8593,6 +8637,24 @@
"product_type": 15
}
},
+ {
+ "model": "attribute.attributevariant",
+ "pk": 9,
+ "fields": {
+ "sort_order": null,
+ "attribute": 32,
+ "product_type": 12
+ }
+ },
+ {
+ "model": "attribute.attributevariant",
+ "pk": 10,
+ "fields": {
+ "sort_order": null,
+ "attribute": 33,
+ "product_type": 12
+ }
+ },
{
"model": "attribute.attributepage",
"pk": 2,
@@ -8945,6 +9007,48 @@
"available_in_grid": false
}
},
+ {
+ "model": "attribute.attribute",
+ "pk": 32,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "slug": "length",
+ "name": "Length",
+ "type": "product-type",
+ "input_type": "numeric",
+ "entity_type": null,
+ "unit": "cm",
+ "value_required": false,
+ "is_variant_only": false,
+ "visible_in_storefront": true,
+ "filterable_in_storefront": true,
+ "filterable_in_dashboard": true,
+ "storefront_search_position": 0,
+ "available_in_grid": true
+ }
+ },
+ {
+ "model": "attribute.attribute",
+ "pk": 33,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "slug": "width",
+ "name": "Width",
+ "type": "product-type",
+ "input_type": "numeric",
+ "entity_type": null,
+ "unit": "cm",
+ "value_required": false,
+ "is_variant_only": false,
+ "visible_in_storefront": true,
+ "filterable_in_storefront": true,
+ "filterable_in_dashboard": true,
+ "storefront_search_position": 0,
+ "available_in_grid": true
+ }
+ },
{
"model": "attribute.attributevalue",
"pk": 1,
@@ -9600,6 +9704,58 @@
"attribute": 31
}
},
+ {
+ "model": "attribute.attributevalue",
+ "pk": 97,
+ "fields": {
+ "sort_order": 0,
+ "name": "55",
+ "value": "",
+ "slug": "55",
+ "file_url": null,
+ "content_type": null,
+ "attribute": 32
+ }
+ },
+ {
+ "model": "attribute.attributevalue",
+ "pk": 98,
+ "fields": {
+ "sort_order": 0,
+ "name": "55",
+ "value": "",
+ "slug": "55",
+ "file_url": null,
+ "content_type": null,
+ "attribute": 33
+ }
+ },
+ {
+ "model": "attribute.attributevalue",
+ "pk": 99,
+ "fields": {
+ "sort_order": 1,
+ "name": "45",
+ "value": "",
+ "slug": "45",
+ "file_url": null,
+ "content_type": null,
+ "attribute": 33
+ }
+ },
+ {
+ "model": "attribute.attributevalue",
+ "pk": 100,
+ "fields": {
+ "sort_order": 1,
+ "name": "45",
+ "value": "",
+ "slug": "45",
+ "file_url": null,
+ "content_type": null,
+ "attribute": 32
+ }
+ },
{
"model": "product.productimage",
"pk": 1,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 5eb099b82b..8f37477c98 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -41,6 +41,7 @@ from ..checkout.models import Checkout
from ..checkout.utils import add_variant_to_checkout
from ..core import JobStatus
from ..core.payments import PaymentInterface
+from ..core.units import MeasurementUnits
from ..core.utils.editorjs import clean_editor_js
from ..csv.events import ExportEvents
from ..csv.models import ExportEvent, ExportFile
@@ -864,6 +865,23 @@ def weight_attribute(db):
return attribute
+def numeric_attribute(db):
+ attribute = Attribute.objects.create(
+ slug="length",
+ name="Length",
+ type=AttributeType.PRODUCT_TYPE,
+ input_type=AttributeInputType.NUMERIC,
+ unit=MeasurementUnits.CM,
+ filterable_in_storefront=True,
+ filterable_in_dashboard=True,
+ available_in_grid=True,
+ )
+ AttributeValue.objects.create(attribute=attribute, name="10", slug="10")
+ AttributeValue.objects.create(attribute=attribute, name="15", slug="15")
+ return attribute
+
+
@pytest.fixture
def file_attribute(db):
attribute = Attribute.objects.create(
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 5ac53f8610..a4ac2c6a2c 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -206,7 +206,7 @@ def test_generate_invoice_payload(fulfilled_order):
"shipping_tax_rate": "0.0000",
"total_net_amount": "80.000",
"total_gross_amount": "98.400",
- "weight": "0.0:kg",
+ "weight": "0.0:g",
},
"number": "01/12/2020/TEST",
"created": ANY,