افزودن ابعاد و وزن کالا با واحد قابل تنظیم برای هر کسبوکار #74
26 changed files with 1215 additions and 20 deletions
|
|
@ -3,11 +3,13 @@ Helper functions for processing product requests (multipart/form-data and JSON)
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
from decimal import Decimal
|
||||||
from typing import Dict, Any, Optional
|
from typing import Dict, Any, Optional
|
||||||
from fastapi import Request, UploadFile, HTTPException
|
from fastapi import Request, UploadFile, HTTPException
|
||||||
from adapters.api.v1.schema_models.product import ProductCreateRequest, ProductUpdateRequest
|
from adapters.api.v1.schema_models.product import ProductCreateRequest, ProductUpdateRequest
|
||||||
from adapters.api.v1.helpers.storage_upload_errors import raise_if_storage_upload_error
|
from adapters.api.v1.helpers.storage_upload_errors import raise_if_storage_upload_error
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
|
from app.core.product_measurements import MEASUREMENT_FIELDS
|
||||||
|
|
||||||
_ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
|
_ALLOWED_IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
|
||||||
|
|
||||||
|
|
@ -72,6 +74,13 @@ async def process_product_request(
|
||||||
if not isinstance(body_data, dict):
|
if not isinstance(body_data, dict):
|
||||||
raise ApiError("INVALID_PAYLOAD", "دادههای ارسالی باید یک object JSON باشد", http_status=400)
|
raise ApiError("INVALID_PAYLOAD", "دادههای ارسالی باید یک object JSON باشد", http_status=400)
|
||||||
|
|
||||||
|
decimal_fields = [key for key in MEASUREMENT_FIELDS if isinstance(body_data.get(key), float)]
|
||||||
|
if decimal_fields:
|
||||||
|
# Keep the JSON number's original precision without changing other product fields.
|
||||||
|
original = getattr(request.state, "original_product_json", None)
|
||||||
|
exact_data = json.loads(original or await request.body(), parse_float=Decimal)
|
||||||
|
body_data.update((key, exact_data[key]) for key in decimal_fields)
|
||||||
|
|
||||||
if is_update and 'default_warehouse_id' in body_data:
|
if is_update and 'default_warehouse_id' in body_data:
|
||||||
default_warehouse_id_value = body_data.get('default_warehouse_id')
|
default_warehouse_id_value = body_data.get('default_warehouse_id')
|
||||||
body_data['default_warehouse_id'] = default_warehouse_id_value
|
body_data['default_warehouse_id'] = default_warehouse_id_value
|
||||||
|
|
@ -150,6 +159,9 @@ def _parse_form_data(form_data) -> Dict[str, Any]:
|
||||||
for key, value in form_data.items():
|
for key, value in form_data.items():
|
||||||
if key == "file":
|
if key == "file":
|
||||||
continue
|
continue
|
||||||
|
if key in MEASUREMENT_FIELDS:
|
||||||
|
product_data[key] = value
|
||||||
|
continue
|
||||||
if isinstance(value, str):
|
if isinstance(value, str):
|
||||||
try:
|
try:
|
||||||
parsed = json.loads(value)
|
parsed = json.loads(value)
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,46 @@ Schema models کامل برای محصولات (Products)
|
||||||
|
|
||||||
این ماژول شامل تمام schema های مورد نیاز برای مدیریت محصولات است.
|
این ماژول شامل تمام schema های مورد نیاز برای مدیریت محصولات است.
|
||||||
"""
|
"""
|
||||||
from typing import Optional, List, Literal, Dict, Any
|
from typing import Annotated, Optional, List, Literal, Dict, Any
|
||||||
from pydantic import BaseModel, Field, field_validator, model_validator, ValidationInfo, ConfigDict
|
from pydantic import BaseModel, BeforeValidator, Field, field_validator, model_validator, ValidationInfo, ConfigDict
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
import re
|
||||||
|
|
||||||
|
from app.core.product_measurements import MEASUREMENT_FIELDS, MEASUREMENT_PRECISION, MEASUREMENT_SCALE
|
||||||
|
|
||||||
|
|
||||||
|
def _measurement_decimal(value: Any) -> Decimal | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(value, str):
|
||||||
|
value = value.strip()
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
if re.fullmatch(r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)", value):
|
||||||
|
return Decimal(value)
|
||||||
|
elif type(value) is int:
|
||||||
|
return Decimal(value)
|
||||||
|
elif isinstance(value, Decimal) and value.is_finite() and not value.is_signed():
|
||||||
|
return value
|
||||||
|
raise ValueError("مقدار باید عدد صحیح یا اعشاری غیرمنفی باشد")
|
||||||
|
|
||||||
|
|
||||||
|
PhysicalMeasurement = Annotated[
|
||||||
|
Annotated[
|
||||||
|
Decimal,
|
||||||
|
Field(ge=0, max_digits=MEASUREMENT_PRECISION, decimal_places=MEASUREMENT_SCALE),
|
||||||
|
] | None,
|
||||||
|
BeforeValidator(_measurement_decimal),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ProductMeasurementsMixin(BaseModel):
|
||||||
|
length_mm: PhysicalMeasurement = Field(None, description=MEASUREMENT_FIELDS["length_mm"])
|
||||||
|
width_mm: PhysicalMeasurement = Field(None, description=MEASUREMENT_FIELDS["width_mm"])
|
||||||
|
height_mm: PhysicalMeasurement = Field(None, description=MEASUREMENT_FIELDS["height_mm"])
|
||||||
|
weight_g: PhysicalMeasurement = Field(None, description=MEASUREMENT_FIELDS["weight_g"])
|
||||||
|
|
||||||
|
|
||||||
class ProductItemType(str, Enum):
|
class ProductItemType(str, Enum):
|
||||||
|
|
@ -167,7 +202,7 @@ class ProductCatalogProfileMixin(BaseModel):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ProductCreateRequest(ProductCatalogProfileMixin):
|
class ProductCreateRequest(ProductCatalogProfileMixin, ProductMeasurementsMixin):
|
||||||
"""درخواست ایجاد محصول جدید"""
|
"""درخواست ایجاد محصول جدید"""
|
||||||
code: Optional[str] = Field(
|
code: Optional[str] = Field(
|
||||||
None,
|
None,
|
||||||
|
|
@ -427,7 +462,7 @@ class ProductCreateRequest(ProductCatalogProfileMixin):
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class ProductUpdateRequest(ProductCatalogProfileMixin):
|
class ProductUpdateRequest(ProductCatalogProfileMixin, ProductMeasurementsMixin):
|
||||||
"""درخواست ویرایش محصول"""
|
"""درخواست ویرایش محصول"""
|
||||||
code: Optional[str] = Field(None, max_length=50)
|
code: Optional[str] = Field(None, max_length=50)
|
||||||
name: Optional[str] = Field(None, max_length=200)
|
name: Optional[str] = Field(None, max_length=200)
|
||||||
|
|
@ -552,6 +587,11 @@ class ProductInventoryInfo(BaseModel):
|
||||||
|
|
||||||
class ProductResponse(BaseModel):
|
class ProductResponse(BaseModel):
|
||||||
"""پاسخ اطلاعات محصول"""
|
"""پاسخ اطلاعات محصول"""
|
||||||
|
length_mm: str | None = Field(None, description=MEASUREMENT_FIELDS["length_mm"])
|
||||||
|
width_mm: str | None = Field(None, description=MEASUREMENT_FIELDS["width_mm"])
|
||||||
|
height_mm: str | None = Field(None, description=MEASUREMENT_FIELDS["height_mm"])
|
||||||
|
weight_g: str | None = Field(None, description=MEASUREMENT_FIELDS["weight_g"])
|
||||||
|
|
||||||
id: int = Field(..., description="شناسه محصول")
|
id: int = Field(..., description="شناسه محصول")
|
||||||
code: str = Field(..., description="کد محصول")
|
code: str = Field(..., description="کد محصول")
|
||||||
name: str = Field(..., description="نام محصول")
|
name: str = Field(..., description="نام محصول")
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from typing import Any, Dict, List, Optional, Union, Generic, TypeVar, Literal
|
||||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator, validator
|
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator, validator
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from datetime import datetime, date
|
from datetime import datetime, date
|
||||||
|
from app.core.product_measurements import ProductDimensionUnit, ProductWeightUnit
|
||||||
|
|
||||||
T = TypeVar('T')
|
T = TypeVar('T')
|
||||||
|
|
||||||
|
|
@ -782,6 +783,9 @@ class BusinessCreateRequest(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
class BusinessUpdateRequest(BaseModel):
|
class BusinessUpdateRequest(BaseModel):
|
||||||
|
product_dimension_unit: ProductDimensionUnit = "mm"
|
||||||
|
product_weight_unit: ProductWeightUnit = "g"
|
||||||
|
|
||||||
name: Optional[str] = Field(default=None, min_length=1, max_length=255, description="نام کسب و کار")
|
name: Optional[str] = Field(default=None, min_length=1, max_length=255, description="نام کسب و کار")
|
||||||
business_type: Optional[BusinessType] = Field(default=None, description="نوع کسب و کار")
|
business_type: Optional[BusinessType] = Field(default=None, description="نوع کسب و کار")
|
||||||
business_field: Optional[BusinessField] = Field(default=None, description="زمینه فعالیت")
|
business_field: Optional[BusinessField] = Field(default=None, description="زمینه فعالیت")
|
||||||
|
|
@ -1175,6 +1179,9 @@ class BusinessUpdateRequest(BaseModel):
|
||||||
|
|
||||||
|
|
||||||
class BusinessResponse(BaseModel):
|
class BusinessResponse(BaseModel):
|
||||||
|
product_dimension_unit: ProductDimensionUnit = "mm"
|
||||||
|
product_weight_unit: ProductWeightUnit = "g"
|
||||||
|
|
||||||
id: int = Field(..., description="شناسه کسب و کار")
|
id: int = Field(..., description="شناسه کسب و کار")
|
||||||
name: str = Field(..., description="نام کسب و کار")
|
name: str = Field(..., description="نام کسب و کار")
|
||||||
business_type: str = Field(..., description="نوع کسب و کار")
|
business_type: str = Field(..., description="نوع کسب و کار")
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,9 @@ class Business(Base):
|
||||||
business_field: Mapped[BusinessField] = mapped_column(SQLEnum(BusinessField), nullable=False)
|
business_field: Mapped[BusinessField] = mapped_column(SQLEnum(BusinessField), nullable=False)
|
||||||
owner_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
owner_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
default_currency_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("currencies.id", ondelete="RESTRICT"), nullable=True, index=True)
|
default_currency_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("currencies.id", ondelete="RESTRICT"), nullable=True, index=True)
|
||||||
|
|
||||||
|
product_dimension_unit: Mapped[str] = mapped_column(String(2), default="mm", server_default="mm")
|
||||||
|
product_weight_unit: Mapped[str] = mapped_column(String(2), default="g", server_default="g")
|
||||||
|
|
||||||
# فیلدهای جدید
|
# فیلدهای جدید
|
||||||
address: Mapped[str | None] = mapped_column(Text, nullable=True)
|
address: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ from sqlalchemy import (
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
from adapters.db.session import Base
|
from adapters.db.session import Base
|
||||||
|
from app.core.product_measurements import MEASUREMENT_PRECISION, MEASUREMENT_SCALE
|
||||||
|
|
||||||
|
|
||||||
class ProductItemType(str, Enum):
|
class ProductItemType(str, Enum):
|
||||||
|
|
@ -55,6 +56,11 @@ class Product(Base):
|
||||||
name: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
name: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
|
length_mm: Mapped[Decimal | None] = mapped_column(Numeric(MEASUREMENT_PRECISION, MEASUREMENT_SCALE))
|
||||||
|
width_mm: Mapped[Decimal | None] = mapped_column(Numeric(MEASUREMENT_PRECISION, MEASUREMENT_SCALE))
|
||||||
|
height_mm: Mapped[Decimal | None] = mapped_column(Numeric(MEASUREMENT_PRECISION, MEASUREMENT_SCALE))
|
||||||
|
weight_g: Mapped[Decimal | None] = mapped_column(Numeric(MEASUREMENT_PRECISION, MEASUREMENT_SCALE))
|
||||||
|
|
||||||
# بارکدهای عمومی (چند مقدار با ویرگول؛ برای اسکن و چاپ برچسب)
|
# بارکدهای عمومی (چند مقدار با ویرگول؛ برای اسکن و چاپ برچسب)
|
||||||
general_barcodes: Mapped[str | None] = mapped_column(
|
general_barcodes: Mapped[str | None] = mapped_column(
|
||||||
Text,
|
Text,
|
||||||
|
|
|
||||||
|
|
@ -417,6 +417,10 @@ class ProductRepository(BaseRepository[Product]):
|
||||||
return None
|
return None
|
||||||
# اجازه بده فیلدهای خاص حتی اگر None باشند هم ست شوند
|
# اجازه بده فیلدهای خاص حتی اگر None باشند هم ست شوند
|
||||||
nullable_overrides = {
|
nullable_overrides = {
|
||||||
|
"length_mm",
|
||||||
|
"width_mm",
|
||||||
|
"height_mm",
|
||||||
|
"weight_g",
|
||||||
"main_unit_id",
|
"main_unit_id",
|
||||||
"secondary_unit_id",
|
"secondary_unit_id",
|
||||||
"unit_conversion_factor",
|
"unit_conversion_factor",
|
||||||
|
|
|
||||||
13
hesabixAPI/app/core/product_measurements.py
Normal file
13
hesabixAPI/app/core/product_measurements.py
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
ProductDimensionUnit = Literal["um", "mm", "cm", "dm", "m", "km", "in", "ft", "yd", "mi"]
|
||||||
|
ProductWeightUnit = Literal["ug", "mg", "g", "kg", "t", "oz", "lb"]
|
||||||
|
|
||||||
|
MEASUREMENT_PRECISION = 27
|
||||||
|
MEASUREMENT_SCALE = 15
|
||||||
|
MEASUREMENT_FIELDS = {
|
||||||
|
"length_mm": "طول به میلیمتر",
|
||||||
|
"width_mm": "عرض به میلیمتر",
|
||||||
|
"height_mm": "ارتفاع به میلیمتر",
|
||||||
|
"weight_g": "وزن به گرم",
|
||||||
|
}
|
||||||
|
|
@ -8,6 +8,7 @@ from __future__ import annotations
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
from typing import Optional, Callable
|
from typing import Optional, Callable
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
|
|
@ -28,6 +29,7 @@ EXCLUDED_PATHS = {
|
||||||
"/api/v1/jobs",
|
"/api/v1/jobs",
|
||||||
"/api/v1/admin",
|
"/api/v1/admin",
|
||||||
}
|
}
|
||||||
|
PRODUCT_DETAIL_PATH = re.compile(r"/api/v1/products/business/[0-9]+/[0-9]+/?")
|
||||||
|
|
||||||
# Endpoints که باید cache شوند (با TTL مشخص)
|
# Endpoints که باید cache شوند (با TTL مشخص)
|
||||||
CACHE_CONFIG = {
|
CACHE_CONFIG = {
|
||||||
|
|
@ -127,6 +129,10 @@ class ResponseCacheMiddleware(BaseHTTPMiddleware):
|
||||||
# فقط GET requests را cache میکنیم
|
# فقط GET requests را cache میکنیم
|
||||||
if request.method != "GET":
|
if request.method != "GET":
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
|
# The product editor needs current values immediately after saving.
|
||||||
|
if PRODUCT_DETAIL_PATH.fullmatch(request.url.path):
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
# بررسی exclude paths
|
# بررسی exclude paths
|
||||||
for excluded_path in EXCLUDED_PATHS:
|
for excluded_path in EXCLUDED_PATHS:
|
||||||
|
|
|
||||||
|
|
@ -909,6 +909,9 @@ def create_app() -> FastAPI:
|
||||||
if raw_body:
|
if raw_body:
|
||||||
try:
|
try:
|
||||||
normalized_body = smart_normalize_json(raw_body)
|
normalized_body = smart_normalize_json(raw_body)
|
||||||
|
if path.startswith(f"{settings.api_v1_prefix}/products/business/"):
|
||||||
|
# Product measurements may need the exact JSON number tokens.
|
||||||
|
request.state.original_product_json = raw_body
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
import logging
|
import logging
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ from __future__ import annotations
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from app.core.product_measurements import MEASUREMENT_FIELDS
|
||||||
|
|
||||||
_LINE_ROOT_TO_EXTRA = (
|
_LINE_ROOT_TO_EXTRA = (
|
||||||
"unit_price",
|
"unit_price",
|
||||||
"line_discount",
|
"line_discount",
|
||||||
|
|
@ -2642,6 +2644,10 @@ _PRODUCT_OPENING_BALANCE_SCHEMA: Dict[str, Any] = {
|
||||||
}
|
}
|
||||||
|
|
||||||
_PRODUCT_WRITE_FIELDS_SCHEMA: Dict[str, Any] = {
|
_PRODUCT_WRITE_FIELDS_SCHEMA: Dict[str, Any] = {
|
||||||
|
**{
|
||||||
|
key: {"type": ["string", "null"], "description": f"{label} (رشتهٔ اعشاری دقیق)"}
|
||||||
|
for key, label in MEASUREMENT_FIELDS.items()
|
||||||
|
},
|
||||||
"item_type": {
|
"item_type": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": ["کالا", "خدمت"],
|
"enum": ["کالا", "خدمت"],
|
||||||
|
|
@ -2980,6 +2986,7 @@ def _normalize_product_opening_balance(raw: Any) -> Optional[Dict[str, Any]]:
|
||||||
|
|
||||||
|
|
||||||
def _apply_product_write_fields(args: Dict[str, Any], payload: Dict[str, Any]) -> None:
|
def _apply_product_write_fields(args: Dict[str, Any], payload: Dict[str, Any]) -> None:
|
||||||
|
payload.update((key, args[key]) for key in MEASUREMENT_FIELDS if key in args)
|
||||||
if "item_type" in args:
|
if "item_type" in args:
|
||||||
payload["item_type"] = normalize_product_item_type(args.get("item_type"))
|
payload["item_type"] = normalize_product_item_type(args.get("item_type"))
|
||||||
if "code" in args:
|
if "code" in args:
|
||||||
|
|
|
||||||
|
|
@ -1716,6 +1716,8 @@ def _business_to_dict(business: Business) -> Dict[str, Any]:
|
||||||
getattr(business, "invoice_default_warehouse_fill_document_header", True),
|
getattr(business, "invoice_default_warehouse_fill_document_header", True),
|
||||||
),
|
),
|
||||||
"allow_negative_inventory_for_bulk": bool(getattr(business, "allow_negative_inventory_for_bulk", False)),
|
"allow_negative_inventory_for_bulk": bool(getattr(business, "allow_negative_inventory_for_bulk", False)),
|
||||||
|
"product_dimension_unit": business.product_dimension_unit,
|
||||||
|
"product_weight_unit": business.product_weight_unit,
|
||||||
"allow_negative_inventory_for_unique": bool(getattr(business, "allow_negative_inventory_for_unique", False)),
|
"allow_negative_inventory_for_unique": bool(getattr(business, "allow_negative_inventory_for_unique", False)),
|
||||||
"warehouse_transfer_require_positive_stock": bool(
|
"warehouse_transfer_require_positive_stock": bool(
|
||||||
getattr(business, "warehouse_transfer_require_positive_stock", True),
|
getattr(business, "warehouse_transfer_require_positive_stock", True),
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import uuid as uuid_module
|
||||||
|
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
from app.core.cache import get_cache
|
from app.core.cache import get_cache
|
||||||
|
from app.core.product_measurements import MEASUREMENT_FIELDS
|
||||||
from adapters.db.models.product import Product, ProductItemType
|
from adapters.db.models.product import Product, ProductItemType
|
||||||
from adapters.db.models.product_attribute import ProductAttribute
|
from adapters.db.models.product_attribute import ProductAttribute
|
||||||
from adapters.db.models.product_attribute_link import ProductAttributeLink
|
from adapters.db.models.product_attribute_link import ProductAttributeLink
|
||||||
|
|
@ -550,6 +551,7 @@ def create_product(
|
||||||
code=code,
|
code=code,
|
||||||
name=payload.name.strip(),
|
name=payload.name.strip(),
|
||||||
description=payload.description,
|
description=payload.description,
|
||||||
|
**payload.model_dump(include=set(MEASUREMENT_FIELDS), exclude_unset=True),
|
||||||
category_id=payload.category_id,
|
category_id=payload.category_id,
|
||||||
main_unit=main_unit,
|
main_unit=main_unit,
|
||||||
secondary_unit=secondary_unit,
|
secondary_unit=secondary_unit,
|
||||||
|
|
@ -1040,6 +1042,7 @@ def update_product(
|
||||||
),
|
),
|
||||||
**catalog_uuid_kw,
|
**catalog_uuid_kw,
|
||||||
**catalog_profile_kw,
|
**catalog_profile_kw,
|
||||||
|
**payload.model_dump(include=set(MEASUREMENT_FIELDS), exclude_unset=True),
|
||||||
**gb_kw,
|
**gb_kw,
|
||||||
**price_update_kwargs,
|
**price_update_kwargs,
|
||||||
**_expiry_update_kwargs(payload, fields_set, obj),
|
**_expiry_update_kwargs(payload, fields_set, obj),
|
||||||
|
|
@ -1530,6 +1533,7 @@ def _get_thumbnail_url(obj: Product) -> str | None:
|
||||||
|
|
||||||
|
|
||||||
def _to_dict(obj: Product, db: Optional[Session] = None) -> Dict[str, Any]:
|
def _to_dict(obj: Product, db: Optional[Session] = None) -> Dict[str, Any]:
|
||||||
|
measurements = {key: getattr(obj, key) for key in MEASUREMENT_FIELDS}
|
||||||
# دریافت attribute_ids از ProductAttributeLink
|
# دریافت attribute_ids از ProductAttributeLink
|
||||||
attribute_ids = []
|
attribute_ids = []
|
||||||
if db is not None:
|
if db is not None:
|
||||||
|
|
@ -1543,6 +1547,10 @@ def _to_dict(obj: Product, db: Optional[Session] = None) -> Dict[str, Any]:
|
||||||
"code": obj.code,
|
"code": obj.code,
|
||||||
"name": obj.name,
|
"name": obj.name,
|
||||||
"description": obj.description,
|
"description": obj.description,
|
||||||
|
**{
|
||||||
|
key: format(value, "f") if value is not None else None
|
||||||
|
for key, value in measurements.items()
|
||||||
|
},
|
||||||
"category_id": obj.category_id,
|
"category_id": obj.category_id,
|
||||||
"main_unit": obj.main_unit,
|
"main_unit": obj.main_unit,
|
||||||
"secondary_unit": obj.secondary_unit,
|
"secondary_unit": obj.secondary_unit,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
"""Store product measurements and business display units."""
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "20261123_000001_product_measurements"
|
||||||
|
down_revision = "20261110_000009_merge_crm_enterprise_and_oa_letter_ocr_heads"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
MEASUREMENT_COLUMNS = ("length_mm", "width_mm", "height_mm", "weight_g")
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"businesses",
|
||||||
|
sa.Column("product_dimension_unit", sa.String(2), nullable=False, server_default="mm"),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
"businesses",
|
||||||
|
sa.Column("product_weight_unit", sa.String(2), nullable=False, server_default="g"),
|
||||||
|
)
|
||||||
|
for column in MEASUREMENT_COLUMNS:
|
||||||
|
op.add_column("products", sa.Column(column, sa.Numeric(18, 6), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for column in reversed(MEASUREMENT_COLUMNS):
|
||||||
|
op.drop_column("products", column)
|
||||||
|
op.drop_column("businesses", "product_weight_unit")
|
||||||
|
op.drop_column("businesses", "product_dimension_unit")
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
"""Extend product measurement precision for imperial units."""
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "20261123_000002_product_measurement_units"
|
||||||
|
down_revision = "20261123_000001_product_measurements"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
MEASUREMENT_COLUMNS = ("length_mm", "width_mm", "height_mm", "weight_g")
|
||||||
|
|
||||||
|
|
||||||
|
def _alter_measurements(previous_type: sa.Numeric, new_type: sa.Numeric) -> None:
|
||||||
|
for column in MEASUREMENT_COLUMNS:
|
||||||
|
op.alter_column("products", column, existing_type=previous_type, type_=new_type)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
_alter_measurements(sa.Numeric(18, 6), sa.Numeric(27, 15))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM businesses
|
||||||
|
WHERE product_dimension_unit NOT IN ('mm', 'cm', 'm')
|
||||||
|
OR product_weight_unit NOT IN ('g', 'kg', 't')
|
||||||
|
) THEN
|
||||||
|
RAISE EXCEPTION 'Restore the original product display units before downgrading';
|
||||||
|
END IF;
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM products
|
||||||
|
WHERE length_mm <> trunc(length_mm, 6)
|
||||||
|
OR width_mm <> trunc(width_mm, 6)
|
||||||
|
OR height_mm <> trunc(height_mm, 6)
|
||||||
|
OR weight_g <> trunc(weight_g, 6)
|
||||||
|
) THEN
|
||||||
|
RAISE EXCEPTION 'Product measurements would lose precision on downgrade';
|
||||||
|
END IF;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
""")
|
||||||
|
_alter_measurements(sa.Numeric(27, 15), sa.Numeric(18, 6))
|
||||||
198
hesabixAPI/tests/test_product_measurements.py
Normal file
198
hesabixAPI/tests/test_product_measurements.py
Normal file
|
|
@ -0,0 +1,198 @@
|
||||||
|
import os
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from adapters.api.v1.helpers.product_request_helper import process_product_request
|
||||||
|
from adapters.api.v1.schema_models.product import ProductUpdateRequest
|
||||||
|
from app.core.product_measurements import MEASUREMENT_FIELDS
|
||||||
|
from app.core.response_cache import ResponseCacheMiddleware
|
||||||
|
from app.core.smart_normalizer import smart_normalize_json
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", ["-1", "-0", "NaN", "1e2", "abc", True, "0.0000000000000001", "1000000000000"])
|
||||||
|
def test_invalid_canonical_measurements(value):
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
ProductUpdateRequest(length_mm=value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_product_measurement_request_parses_json_and_multipart_exactly():
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
@app.post("/")
|
||||||
|
async def echo_measurements(request: Request):
|
||||||
|
payload, _, _ = await process_product_request(request, 1, None, None, is_update=True)
|
||||||
|
return payload.model_dump(mode="json", exclude_unset=True)
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def normalize_json(request, call_next):
|
||||||
|
if request.headers.get("content-type") == "application/json":
|
||||||
|
raw = await request.body()
|
||||||
|
request.state.original_product_json = raw
|
||||||
|
request._body = smart_normalize_json(raw)
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
with TestClient(app) as client:
|
||||||
|
response = client.post(
|
||||||
|
"/",
|
||||||
|
content='{"length_mm":999999999999.999999999999999,"width_mm":0,"height_mm":null}',
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
assert response.json() == {
|
||||||
|
"length_mm": "999999999999.999999999999999",
|
||||||
|
"width_mm": "0",
|
||||||
|
"height_mm": None,
|
||||||
|
}
|
||||||
|
response = client.post(
|
||||||
|
"/",
|
||||||
|
files={"weight_g": (None, "999999999999.999999999999999"), "length_mm": (None, "")},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
assert response.json() == {"weight_g": "999999999999.999999999999999", "length_mm": None}
|
||||||
|
|
||||||
|
|
||||||
|
def test_product_detail_reads_current_values_with_response_cache_middleware(monkeypatch):
|
||||||
|
from app.core import response_cache
|
||||||
|
|
||||||
|
def unexpected_cache_access():
|
||||||
|
pytest.fail("the product detail read must reach the route even if the cache is enabled")
|
||||||
|
|
||||||
|
monkeypatch.setattr(response_cache, "get_cache", unexpected_cache_access)
|
||||||
|
app = FastAPI()
|
||||||
|
app.add_middleware(ResponseCacheMiddleware)
|
||||||
|
current = {"weight_g": "1250.500000"}
|
||||||
|
|
||||||
|
@app.get("/api/v1/products/business/1/2")
|
||||||
|
def detail():
|
||||||
|
return {"success": True, "data": current}
|
||||||
|
|
||||||
|
with TestClient(app) as client:
|
||||||
|
assert client.get("/api/v1/products/business/1/2").json()["data"] == current
|
||||||
|
current["weight_g"] = "1250.625000"
|
||||||
|
assert client.get("/api/v1/products/business/1/2").json()["data"] == current
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(
|
||||||
|
os.getenv("HESABIX_TEST_PRODUCT_MEASUREMENTS") != "1",
|
||||||
|
reason="requires the isolated PostgreSQL product measurement fixture",
|
||||||
|
)
|
||||||
|
def test_product_measurement_routes_and_postcommit_state():
|
||||||
|
from sqlalchemy import select, text
|
||||||
|
|
||||||
|
from adapters.api.v1.businesses import router as businesses_router
|
||||||
|
from adapters.api.v1.products import router as products_router
|
||||||
|
from adapters.db.models.business import Business
|
||||||
|
from adapters.db.models.product import Product
|
||||||
|
from adapters.db.session import SessionLocal
|
||||||
|
from app.core.error_handlers import register_error_handlers
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
register_error_handlers(app)
|
||||||
|
app.include_router(businesses_router, prefix="/api/v1")
|
||||||
|
app.include_router(products_router, prefix="/api/v1")
|
||||||
|
owner = {"Authorization": "ApiKey measurement-fixture-1"}
|
||||||
|
outsider = {"Authorization": "ApiKey measurement-fixture-2"}
|
||||||
|
businesses_path = "/api/v1/businesses"
|
||||||
|
products_path = "/api/v1/products/business/1"
|
||||||
|
|
||||||
|
def data(response):
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
return response.json()["data"]
|
||||||
|
|
||||||
|
def committed_product(product_id):
|
||||||
|
with SessionLocal() as session:
|
||||||
|
product = session.get(Product, product_id)
|
||||||
|
return tuple(getattr(product, key) for key in MEASUREMENT_FIELDS)
|
||||||
|
|
||||||
|
with SessionLocal() as session:
|
||||||
|
print(session.execute(text("SHOW server_version")).scalar_one())
|
||||||
|
legacy_id = session.scalar(select(Product.id).filter_by(business_id=1, code="LEGACY"))
|
||||||
|
assert legacy_id is not None
|
||||||
|
|
||||||
|
with TestClient(app, headers=owner) as client:
|
||||||
|
def settings(dimension=None, weight=None):
|
||||||
|
update = {}
|
||||||
|
if dimension is not None:
|
||||||
|
update["product_dimension_unit"] = dimension
|
||||||
|
if weight is not None:
|
||||||
|
update["product_weight_unit"] = weight
|
||||||
|
return data(client.put(f"{businesses_path}/1", json=update))
|
||||||
|
|
||||||
|
def product_values(product_id):
|
||||||
|
item = data(client.get(f"{products_path}/{product_id}"))["item"]
|
||||||
|
return tuple(item[key] for key in MEASUREMENT_FIELDS)
|
||||||
|
|
||||||
|
initial = data(client.get(f"{businesses_path}/1"))
|
||||||
|
assert (initial["product_dimension_unit"], initial["product_weight_unit"]) == ("mm", "g")
|
||||||
|
assert product_values(legacy_id) == (None,) * 4
|
||||||
|
data(client.put(f"{products_path}/{legacy_id}", json={"description": "legacy edit"}))
|
||||||
|
assert committed_product(legacy_id) == (None,) * 4
|
||||||
|
|
||||||
|
entered = ("125.5", "22.375", "3.0625", "1250.5")
|
||||||
|
product = data(client.post(products_path, json={
|
||||||
|
"name": "Decimal measurements",
|
||||||
|
**dict(zip(MEASUREMENT_FIELDS, entered, strict=True)),
|
||||||
|
}))
|
||||||
|
product_id = product["id"]
|
||||||
|
expected = tuple(Decimal(value) for value in entered)
|
||||||
|
assert tuple(map(Decimal, product_values(product_id))) == expected
|
||||||
|
assert committed_product(product_id) == expected
|
||||||
|
print("created", committed_product(product_id))
|
||||||
|
|
||||||
|
data(client.put(f"{products_path}/{product_id}", json={"width_mm": "22.8125"}))
|
||||||
|
expected = (expected[0], Decimal("22.8125"), *expected[2:])
|
||||||
|
assert committed_product(product_id) == expected
|
||||||
|
|
||||||
|
dimension_only = settings(dimension="cm")
|
||||||
|
assert dimension_only["product_weight_unit"] == "g"
|
||||||
|
settings(weight="kg")
|
||||||
|
assert committed_product(product_id) == expected
|
||||||
|
settings(dimension="m", weight="t")
|
||||||
|
data(client.put(f"{products_path}/{product_id}", json={"description": "other field"}))
|
||||||
|
assert committed_product(product_id) == expected
|
||||||
|
settings(dimension="mm", weight="g")
|
||||||
|
assert tuple(map(Decimal, product_values(product_id))) == expected
|
||||||
|
print("edited and switched back", committed_product(product_id))
|
||||||
|
|
||||||
|
after_switch = settings(dimension="m", weight="t")
|
||||||
|
assert (after_switch["product_dimension_unit"], after_switch["product_weight_unit"]) == ("m", "t")
|
||||||
|
data(client.put(f"{products_path}/{product_id}", json={"height_mm": "3.125"}))
|
||||||
|
assert committed_product(product_id) == (*expected[:2], Decimal("3.125"), expected[3])
|
||||||
|
print("submitted with the previous form's unit", committed_product(product_id))
|
||||||
|
|
||||||
|
peer = data(client.get(f"{businesses_path}/2"))
|
||||||
|
assert (peer["product_dimension_unit"], peer["product_weight_unit"]) == ("mm", "g")
|
||||||
|
assert client.put(f"{businesses_path}/1", json={"product_dimension_unit": "kg"}).status_code == 422
|
||||||
|
assert client.put(f"{businesses_path}/1", json={"product_weight_unit": None}).status_code == 422
|
||||||
|
assert client.put(f"{businesses_path}/1", headers=outsider, json={"product_weight_unit": "g"}).status_code == 403
|
||||||
|
assert client.put(f"{products_path}/{product_id}", json={"weight_g": "-5"}).status_code == 400
|
||||||
|
assert client.put(f"/api/v1/products/business/2/{product_id}", json={"weight_g": "5"}).status_code in (403, 404)
|
||||||
|
with SessionLocal() as session:
|
||||||
|
assert session.get(Business, 1).product_weight_unit == "t"
|
||||||
|
assert session.get(Business, 2).product_weight_unit == "g"
|
||||||
|
|
||||||
|
data(client.put(f"{products_path}/{product_id}", files={"height_mm": (None, "")}))
|
||||||
|
assert committed_product(product_id) == (*expected[:2], None, expected[3])
|
||||||
|
empty = data(client.post(products_path, json={"name": "No measurements"}))
|
||||||
|
assert committed_product(empty["id"]) == (None,) * 4
|
||||||
|
|
||||||
|
for dimension in ("um", "dm", "km", "in", "ft", "yd", "mi"):
|
||||||
|
assert settings(dimension=dimension)["product_dimension_unit"] == dimension
|
||||||
|
for weight in ("ug", "mg", "oz", "lb"):
|
||||||
|
assert settings(weight=weight)["product_weight_unit"] == weight
|
||||||
|
settings(dimension="in", weight="oz")
|
||||||
|
data(client.put(f"{products_path}/{product_id}", json={
|
||||||
|
"height_mm": "31.3580018",
|
||||||
|
"weight_g": "34.999385715861875",
|
||||||
|
}))
|
||||||
|
imperial = (*expected[:2], Decimal("31.3580018"), Decimal("34.999385715861875"))
|
||||||
|
assert committed_product(product_id) == imperial
|
||||||
|
settings(dimension="km", weight="mg")
|
||||||
|
data(client.put(f"{products_path}/{product_id}", json={"description": "imperial precision retained"}))
|
||||||
|
assert committed_product(product_id) == imperial
|
||||||
|
print("imperial input, fixed-point storage", committed_product(product_id))
|
||||||
|
settings(dimension="mm", weight="g")
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../models/product_form_data.dart';
|
import '../models/product_form_data.dart';
|
||||||
|
import '../models/product_measurement.dart';
|
||||||
import '../services/product_service.dart';
|
import '../services/product_service.dart';
|
||||||
import '../services/opening_balance_service.dart';
|
import '../services/opening_balance_service.dart';
|
||||||
import '../services/category_service.dart';
|
import '../services/category_service.dart';
|
||||||
|
|
@ -33,6 +34,10 @@ class ProductFormController extends ChangeNotifier {
|
||||||
late final OpeningBalanceService _openingBalanceService;
|
late final OpeningBalanceService _openingBalanceService;
|
||||||
|
|
||||||
ProductFormData _formData = ProductFormData();
|
ProductFormData _formData = ProductFormData();
|
||||||
|
ProductMeasurementUnit? _dimensionUnit;
|
||||||
|
ProductMeasurementUnit? _weightUnit;
|
||||||
|
Map<ProductMeasurement, String?> _originalMeasurements = const {};
|
||||||
|
final _measurementInputs = <ProductMeasurement, String>{};
|
||||||
bool _isLoading = false;
|
bool _isLoading = false;
|
||||||
String? _errorMessage;
|
String? _errorMessage;
|
||||||
int? _editingProductId;
|
int? _editingProductId;
|
||||||
|
|
@ -409,6 +414,7 @@ class ProductFormController extends ChangeNotifier {
|
||||||
_loadReferenceData(),
|
_loadReferenceData(),
|
||||||
_loadPriceListsAndCurrencies(),
|
_loadPriceListsAndCurrencies(),
|
||||||
_loadWarehouses(),
|
_loadWarehouses(),
|
||||||
|
_loadMeasurementUnits(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (cloneSourceProductId != null) {
|
if (cloneSourceProductId != null) {
|
||||||
|
|
@ -469,6 +475,9 @@ class ProductFormController extends ChangeNotifier {
|
||||||
_originalInventoryMode = 'bulk';
|
_originalInventoryMode = 'bulk';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_originalMeasurements = _formData.physicalMeasurements;
|
||||||
|
_measurementInputs.clear();
|
||||||
|
|
||||||
// دیگر واحد اصلی را بهصورت خودکار مقداردهی نکن؛
|
// دیگر واحد اصلی را بهصورت خودکار مقداردهی نکن؛
|
||||||
// کاربر میتواند عنوان واحد را در فرم وارد کند و در صورت تطبیق با لیست، آیدی ست میشود
|
// کاربر میتواند عنوان واحد را در فرم وارد کند و در صورت تطبیق با لیست، آیدی ست میشود
|
||||||
|
|
||||||
|
|
@ -482,6 +491,77 @@ class ProductFormController extends ChangeNotifier {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _loadMeasurementUnits() async {
|
||||||
|
try {
|
||||||
|
final business = await BusinessApiService.getBusiness(
|
||||||
|
businessId,
|
||||||
|
apiClient: _apiClient,
|
||||||
|
);
|
||||||
|
_dimensionUnit = ProductMeasurementUnit.dimensionFromCode(
|
||||||
|
business.productDimensionUnit,
|
||||||
|
);
|
||||||
|
_weightUnit = ProductMeasurementUnit.weightFromCode(
|
||||||
|
business.productWeightUnit,
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
_dimensionUnit = null;
|
||||||
|
_weightUnit = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ProductMeasurementUnit? measurementUnit(ProductMeasurement field) =>
|
||||||
|
field == ProductMeasurement.weight ? _weightUnit : _dimensionUnit;
|
||||||
|
|
||||||
|
String measurementInput(ProductMeasurement field) =>
|
||||||
|
_measurementInputs[field] ??
|
||||||
|
measurementUnit(field)?.display(_formData.physicalMeasurements[field]) ??
|
||||||
|
'';
|
||||||
|
|
||||||
|
bool isMeasurementApproximate(ProductMeasurement field) {
|
||||||
|
final display = measurementUnit(field)!.format(_originalMeasurements[field]);
|
||||||
|
return display.approximate && (_measurementInputs[field] ?? display.value) == display.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _measurementBaseValue(ProductMeasurement field, String input) =>
|
||||||
|
measurementUnit(field)!.toBaseValue(input, original: _originalMeasurements[field]);
|
||||||
|
|
||||||
|
String? measurementError(ProductMeasurement field, String input) {
|
||||||
|
try {
|
||||||
|
_measurementBaseValue(field, input);
|
||||||
|
return null;
|
||||||
|
} on FormatException catch (error) {
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void updateMeasurement(ProductMeasurement field, String input) {
|
||||||
|
_measurementInputs[field] = input;
|
||||||
|
try {
|
||||||
|
final value = _measurementBaseValue(field, input);
|
||||||
|
updateFormData(_formData.copyWith(physicalMeasurements: {
|
||||||
|
..._formData.physicalMeasurements,
|
||||||
|
field: value,
|
||||||
|
}));
|
||||||
|
} on FormatException {
|
||||||
|
// Keep the raw input for validation, including when the user switches tabs.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, String?> _measurementPayload({required bool editing}) {
|
||||||
|
if (_formData.itemType != 'کالا' || _dimensionUnit == null) return {};
|
||||||
|
final values = <String, String?>{};
|
||||||
|
for (final field in ProductMeasurement.values) {
|
||||||
|
final input = _measurementInputs[field];
|
||||||
|
if (editing && input == null) continue;
|
||||||
|
final value = input == null
|
||||||
|
? _formData.physicalMeasurements[field]
|
||||||
|
: _measurementBaseValue(field, input);
|
||||||
|
if (editing ? value == _originalMeasurements[field] : value == null) continue;
|
||||||
|
values[field.apiKey] = value;
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
// Load all reference data (موازی برای بهبود عملکرد)
|
// Load all reference data (موازی برای بهبود عملکرد)
|
||||||
Future<void> _loadReferenceData() async {
|
Future<void> _loadReferenceData() async {
|
||||||
try {
|
try {
|
||||||
|
|
@ -616,8 +696,16 @@ class ProductFormController extends ChangeNotifier {
|
||||||
_setError(firstError);
|
_setError(firstError);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (!isValid) return false;
|
||||||
return isValid;
|
|
||||||
|
try {
|
||||||
|
_measurementPayload(editing: isEditingProduct);
|
||||||
|
} on FormatException catch (error) {
|
||||||
|
_setError(error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> _ensureCatalogBusinessContactReady() async {
|
Future<bool> _ensureCatalogBusinessContactReady() async {
|
||||||
|
|
@ -659,7 +747,8 @@ class ProductFormController extends ChangeNotifier {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
final payload = _formData.toPayload();
|
final payload = _formData.toPayload()
|
||||||
|
..addAll(_measurementPayload(editing: false));
|
||||||
if (openingBalanceInput != null) {
|
if (openingBalanceInput != null) {
|
||||||
payload['opening_balance'] = openingBalanceInput.toJson();
|
payload['opening_balance'] = openingBalanceInput.toJson();
|
||||||
}
|
}
|
||||||
|
|
@ -763,7 +852,8 @@ class ProductFormController extends ChangeNotifier {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
final payload = _formData.toPayload();
|
final payload = _formData.toPayload()
|
||||||
|
..addAll(_measurementPayload(editing: true));
|
||||||
if (openingBalanceInput != null) {
|
if (openingBalanceInput != null) {
|
||||||
payload['opening_balance'] = openingBalanceInput.toJson();
|
payload['opening_balance'] = openingBalanceInput.toJson();
|
||||||
}
|
}
|
||||||
|
|
@ -943,6 +1033,8 @@ class ProductFormController extends ChangeNotifier {
|
||||||
// Reset form
|
// Reset form
|
||||||
void resetForm() {
|
void resetForm() {
|
||||||
_formData = ProductFormData();
|
_formData = ProductFormData();
|
||||||
|
_originalMeasurements = const {};
|
||||||
|
_measurementInputs.clear();
|
||||||
_clearError();
|
_clearError();
|
||||||
// حذف draft ذخیره شده
|
// حذف draft ذخیره شده
|
||||||
_autoSave.clearFormData(businessId, _editingProductId);
|
_autoSave.clearFormData(businessId, _editingProductId);
|
||||||
|
|
|
||||||
|
|
@ -390,6 +390,8 @@ class BusinessResponse {
|
||||||
final bool invoiceDefaultWarehouseFillDocumentHeader;
|
final bool invoiceDefaultWarehouseFillDocumentHeader;
|
||||||
/// خروج با کسری برای کالای فلهای هنگام قطعی حواله
|
/// خروج با کسری برای کالای فلهای هنگام قطعی حواله
|
||||||
final bool allowNegativeInventoryForBulk;
|
final bool allowNegativeInventoryForBulk;
|
||||||
|
final String productDimensionUnit;
|
||||||
|
final String productWeightUnit;
|
||||||
/// خروج با کسری برای کالای یونیک هنگام قطعی حواله
|
/// خروج با کسری برای کالای یونیک هنگام قطعی حواله
|
||||||
final bool allowNegativeInventoryForUnique;
|
final bool allowNegativeInventoryForUnique;
|
||||||
/// حواله انتقال همیشه کنترل کسری کامل
|
/// حواله انتقال همیشه کنترل کسری کامل
|
||||||
|
|
@ -468,6 +470,8 @@ class BusinessResponse {
|
||||||
this.invoiceDefaultWarehouseId,
|
this.invoiceDefaultWarehouseId,
|
||||||
this.invoiceDefaultWarehouseFillDocumentHeader = true,
|
this.invoiceDefaultWarehouseFillDocumentHeader = true,
|
||||||
this.allowNegativeInventoryForBulk = false,
|
this.allowNegativeInventoryForBulk = false,
|
||||||
|
this.productDimensionUnit = 'mm',
|
||||||
|
this.productWeightUnit = 'g',
|
||||||
this.allowNegativeInventoryForUnique = false,
|
this.allowNegativeInventoryForUnique = false,
|
||||||
this.warehouseTransferRequirePositiveStock = true,
|
this.warehouseTransferRequirePositiveStock = true,
|
||||||
this.goodsExpenseIncomeWorkflowMode = 'simple',
|
this.goodsExpenseIncomeWorkflowMode = 'simple',
|
||||||
|
|
@ -576,6 +580,8 @@ class BusinessResponse {
|
||||||
invoiceDefaultWarehouseFillDocumentHeader:
|
invoiceDefaultWarehouseFillDocumentHeader:
|
||||||
(json['invoice_default_warehouse_fill_document_header'] as bool?) ?? true,
|
(json['invoice_default_warehouse_fill_document_header'] as bool?) ?? true,
|
||||||
allowNegativeInventoryForBulk: (json['allow_negative_inventory_for_bulk'] as bool?) ?? false,
|
allowNegativeInventoryForBulk: (json['allow_negative_inventory_for_bulk'] as bool?) ?? false,
|
||||||
|
productDimensionUnit: (json['product_dimension_unit'] as String?) ?? 'mm',
|
||||||
|
productWeightUnit: (json['product_weight_unit'] as String?) ?? 'g',
|
||||||
allowNegativeInventoryForUnique: (json['allow_negative_inventory_for_unique'] as bool?) ?? false,
|
allowNegativeInventoryForUnique: (json['allow_negative_inventory_for_unique'] as bool?) ?? false,
|
||||||
warehouseTransferRequirePositiveStock:
|
warehouseTransferRequirePositiveStock:
|
||||||
(json['warehouse_transfer_require_positive_stock'] as bool?) ?? true,
|
(json['warehouse_transfer_require_positive_stock'] as bool?) ?? true,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import 'catalog_specification_item.dart';
|
import 'catalog_specification_item.dart';
|
||||||
|
import 'product_measurement.dart';
|
||||||
import 'product_supplier_item.dart';
|
import 'product_supplier_item.dart';
|
||||||
|
|
||||||
const Object _kProductFormCodeUnset = Object();
|
const Object _kProductFormCodeUnset = Object();
|
||||||
|
|
@ -20,6 +21,7 @@ class ProductFormData {
|
||||||
/// بارکدهای عمومی؛ با ویرگول از هم جدا میشوند (همعرض با APIی `general_barcodes`).
|
/// بارکدهای عمومی؛ با ویرگول از هم جدا میشوند (همعرض با APIی `general_barcodes`).
|
||||||
String? generalBarcodes;
|
String? generalBarcodes;
|
||||||
int? categoryId;
|
int? categoryId;
|
||||||
|
final Map<ProductMeasurement, String?> physicalMeasurements;
|
||||||
|
|
||||||
// Inventory
|
// Inventory
|
||||||
bool trackInventory;
|
bool trackInventory;
|
||||||
|
|
@ -102,6 +104,7 @@ class ProductFormData {
|
||||||
this.description,
|
this.description,
|
||||||
this.generalBarcodes,
|
this.generalBarcodes,
|
||||||
this.categoryId,
|
this.categoryId,
|
||||||
|
this.physicalMeasurements = const {},
|
||||||
this.trackInventory = false,
|
this.trackInventory = false,
|
||||||
this.reorderPoint,
|
this.reorderPoint,
|
||||||
this.minOrderQty,
|
this.minOrderQty,
|
||||||
|
|
@ -164,6 +167,7 @@ class ProductFormData {
|
||||||
Object? description = _kProductFormFieldUnset,
|
Object? description = _kProductFormFieldUnset,
|
||||||
Object? generalBarcodes = _kProductFormFieldUnset,
|
Object? generalBarcodes = _kProductFormFieldUnset,
|
||||||
Object? categoryId = _kProductFormFieldUnset,
|
Object? categoryId = _kProductFormFieldUnset,
|
||||||
|
Map<ProductMeasurement, String?>? physicalMeasurements,
|
||||||
bool? trackInventory,
|
bool? trackInventory,
|
||||||
Object? reorderPoint = _kProductFormFieldUnset,
|
Object? reorderPoint = _kProductFormFieldUnset,
|
||||||
Object? minOrderQty = _kProductFormFieldUnset,
|
Object? minOrderQty = _kProductFormFieldUnset,
|
||||||
|
|
@ -221,6 +225,7 @@ class ProductFormData {
|
||||||
description: _nullableCopyField<String>(description, this.description),
|
description: _nullableCopyField<String>(description, this.description),
|
||||||
generalBarcodes: _nullableCopyField<String>(generalBarcodes, this.generalBarcodes),
|
generalBarcodes: _nullableCopyField<String>(generalBarcodes, this.generalBarcodes),
|
||||||
categoryId: _nullableCopyField<int>(categoryId, this.categoryId),
|
categoryId: _nullableCopyField<int>(categoryId, this.categoryId),
|
||||||
|
physicalMeasurements: physicalMeasurements ?? this.physicalMeasurements,
|
||||||
trackInventory: trackInventory ?? this.trackInventory,
|
trackInventory: trackInventory ?? this.trackInventory,
|
||||||
reorderPoint: _nullableCopyField<int>(reorderPoint, this.reorderPoint),
|
reorderPoint: _nullableCopyField<int>(reorderPoint, this.reorderPoint),
|
||||||
minOrderQty: _nullableCopyField<int>(minOrderQty, this.minOrderQty),
|
minOrderQty: _nullableCopyField<int>(minOrderQty, this.minOrderQty),
|
||||||
|
|
@ -386,6 +391,10 @@ class ProductFormData {
|
||||||
|
|
||||||
factory ProductFormData.fromProduct(Map<String, dynamic> product) {
|
factory ProductFormData.fromProduct(Map<String, dynamic> product) {
|
||||||
return ProductFormData(
|
return ProductFormData(
|
||||||
|
physicalMeasurements: {
|
||||||
|
for (final field in ProductMeasurement.values)
|
||||||
|
field: product[field.apiKey] as String?,
|
||||||
|
},
|
||||||
itemType: (product['item_type'] as String?) ?? 'کالا',
|
itemType: (product['item_type'] as String?) ?? 'کالا',
|
||||||
code: product['code']?.toString(),
|
code: product['code']?.toString(),
|
||||||
autoGenerateCode: false,
|
autoGenerateCode: false,
|
||||||
|
|
|
||||||
129
hesabixUI/hesabix_ui/lib/models/product_measurement.dart
Normal file
129
hesabixUI/hesabix_ui/lib/models/product_measurement.dart
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
import '../utils/number_normalizer.dart';
|
||||||
|
|
||||||
|
enum ProductMeasurementUnit {
|
||||||
|
um('میکرومتر', '0.001'),
|
||||||
|
mm('میلیمتر', '1'),
|
||||||
|
cm('سانتیمتر', '10'),
|
||||||
|
dm('دسیمتر', '100'),
|
||||||
|
m('متر', '1000'),
|
||||||
|
km('کیلومتر', '1000000'),
|
||||||
|
inch('اینچ', '25.4', code: 'in'),
|
||||||
|
ft('فوت', '304.8'),
|
||||||
|
yd('یارد', '914.4'),
|
||||||
|
mi('مایل', '1609344'),
|
||||||
|
ug('میکروگرم', '0.000001'),
|
||||||
|
mg('میلیگرم', '0.001'),
|
||||||
|
g('گرم', '1'),
|
||||||
|
kg('کیلوگرم', '1000'),
|
||||||
|
t('تن متریک', '1000000'),
|
||||||
|
oz('اونس', '28.349523125'),
|
||||||
|
lb('پوند', '453.59237');
|
||||||
|
|
||||||
|
const ProductMeasurementUnit(this.label, this._factor, {String? code})
|
||||||
|
: _code = code;
|
||||||
|
|
||||||
|
static const dimensionUnits = [um, mm, cm, dm, m, km, inch, ft, yd, mi];
|
||||||
|
static const weightUnits = [ug, mg, g, kg, t, oz, lb];
|
||||||
|
|
||||||
|
static ProductMeasurementUnit dimensionFromCode(String code) =>
|
||||||
|
dimensionUnits.firstWhere((unit) => unit.code == code);
|
||||||
|
|
||||||
|
static ProductMeasurementUnit weightFromCode(String code) =>
|
||||||
|
weightUnits.firstWhere((unit) => unit.code == code);
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String _factor;
|
||||||
|
final String? _code;
|
||||||
|
|
||||||
|
String get code => _code ?? name;
|
||||||
|
|
||||||
|
String display(String? baseValue) => format(baseValue).value;
|
||||||
|
|
||||||
|
({String value, bool approximate}) format(String? baseValue) {
|
||||||
|
if (baseValue == null) return (value: '', approximate: false);
|
||||||
|
final base = _readDecimal(baseValue);
|
||||||
|
final factor = _readDecimal(_factor);
|
||||||
|
final places = _storageScale + _factor.split('.').first.length;
|
||||||
|
final numerator = base.coefficient * _powerOfTen(factor.scale + places);
|
||||||
|
final divisor = factor.coefficient * _powerOfTen(base.scale);
|
||||||
|
final remainder = numerator.remainder(divisor);
|
||||||
|
final quotient = numerator ~/ divisor;
|
||||||
|
final rounded = remainder * BigInt.two >= divisor
|
||||||
|
? quotient + BigInt.one
|
||||||
|
: quotient;
|
||||||
|
return (
|
||||||
|
value: _decimalText(rounded, places),
|
||||||
|
approximate: remainder != BigInt.zero,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-entering the displayed value of an existing measurement keeps its exact base value.
|
||||||
|
String? toBaseValue(String input, {String? original}) {
|
||||||
|
final value = _normalizedInput(input);
|
||||||
|
if (value.isEmpty) return null;
|
||||||
|
if (!_decimalPattern.hasMatch(value)) {
|
||||||
|
throw const FormatException('عدد صحیح یا اعشاری غیرمنفی وارد کنید.');
|
||||||
|
}
|
||||||
|
|
||||||
|
final entered = _readDecimal(value);
|
||||||
|
if (original != null &&
|
||||||
|
_decimalText(entered.coefficient, entered.scale) == display(original)) {
|
||||||
|
return original;
|
||||||
|
}
|
||||||
|
|
||||||
|
final factor = _readDecimal(_factor);
|
||||||
|
final base = _decimalText(
|
||||||
|
entered.coefficient * factor.coefficient,
|
||||||
|
entered.scale + factor.scale,
|
||||||
|
);
|
||||||
|
final parts = base.split('.');
|
||||||
|
if (parts.first.length > 12) {
|
||||||
|
throw const FormatException(
|
||||||
|
'مقدار در واحد پایه باید کمتر از ۱٬۰۰۰٬۰۰۰٬۰۰۰٬۰۰۰ باشد.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (parts.length == 2 && parts.last.length > _storageScale) {
|
||||||
|
throw const FormatException(
|
||||||
|
'مقدار در واحد پایه حداکثر میتواند ۱۵ رقم اعشار داشته باشد.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ProductMeasurement {
|
||||||
|
length('length_mm', 'طول'),
|
||||||
|
width('width_mm', 'عرض'),
|
||||||
|
height('height_mm', 'ارتفاع'),
|
||||||
|
weight('weight_g', 'وزن');
|
||||||
|
|
||||||
|
const ProductMeasurement(this.apiKey, this.label);
|
||||||
|
|
||||||
|
final String apiKey;
|
||||||
|
final String label;
|
||||||
|
}
|
||||||
|
|
||||||
|
final _decimalPattern = RegExp(r'^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$');
|
||||||
|
final _trailingZeros = RegExp(r'0+$');
|
||||||
|
const _storageScale = 15;
|
||||||
|
|
||||||
|
String _normalizedInput(String input) =>
|
||||||
|
toEnglishDigits(input.trim()).replaceAll('٫', '.');
|
||||||
|
|
||||||
|
BigInt _powerOfTen(int exponent) => BigInt.from(10).pow(exponent);
|
||||||
|
|
||||||
|
({BigInt coefficient, int scale}) _readDecimal(String value) {
|
||||||
|
final parts = value.split('.');
|
||||||
|
return (
|
||||||
|
coefficient: BigInt.parse(parts.join()),
|
||||||
|
scale: parts.length == 2 ? parts.last.length : 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _decimalText(BigInt coefficient, int scale) {
|
||||||
|
final digits = coefficient.toString().padLeft(scale + 1, '0');
|
||||||
|
final split = digits.length - scale;
|
||||||
|
final whole = digits.substring(0, split);
|
||||||
|
final fraction = digits.substring(split).replaceFirst(_trailingZeros, '');
|
||||||
|
return fraction.isEmpty ? whole : '$whole.$fraction';
|
||||||
|
}
|
||||||
|
|
@ -7,6 +7,7 @@ import 'package:hesabix_ui/l10n/app_localizations.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
import 'package:hesabix_ui/models/account_model.dart';
|
import 'package:hesabix_ui/models/account_model.dart';
|
||||||
import 'package:hesabix_ui/models/business_models.dart';
|
import 'package:hesabix_ui/models/business_models.dart';
|
||||||
|
import 'package:hesabix_ui/models/product_measurement.dart';
|
||||||
import 'package:hesabix_ui/services/account_service.dart';
|
import 'package:hesabix_ui/services/account_service.dart';
|
||||||
import 'package:hesabix_ui/services/business_api_service.dart';
|
import 'package:hesabix_ui/services/business_api_service.dart';
|
||||||
import 'package:hesabix_ui/services/currency_service.dart';
|
import 'package:hesabix_ui/services/currency_service.dart';
|
||||||
|
|
@ -94,6 +95,8 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
bool _allowNegativeInventoryForBulk = false;
|
bool _allowNegativeInventoryForBulk = false;
|
||||||
bool _allowNegativeInventoryForUnique = false;
|
bool _allowNegativeInventoryForUnique = false;
|
||||||
bool _warehouseTransferRequirePositiveStock = true;
|
bool _warehouseTransferRequirePositiveStock = true;
|
||||||
|
ProductMeasurementUnit _productDimensionUnit = ProductMeasurementUnit.mm;
|
||||||
|
ProductMeasurementUnit _productWeightUnit = ProductMeasurementUnit.g;
|
||||||
|
|
||||||
// کالای هزینهشده / کالای درآمدشده
|
// کالای هزینهشده / کالای درآمدشده
|
||||||
String _geiWorkflowMode = 'simple';
|
String _geiWorkflowMode = 'simple';
|
||||||
|
|
@ -231,6 +234,12 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
? resp.invoiceGlobalDiscountMaxAmount!.toStringAsFixed(0)
|
? resp.invoiceGlobalDiscountMaxAmount!.toStringAsFixed(0)
|
||||||
: '';
|
: '';
|
||||||
_allowNegativeInventoryForBulk = resp.allowNegativeInventoryForBulk;
|
_allowNegativeInventoryForBulk = resp.allowNegativeInventoryForBulk;
|
||||||
|
_productDimensionUnit = ProductMeasurementUnit.dimensionFromCode(
|
||||||
|
resp.productDimensionUnit,
|
||||||
|
);
|
||||||
|
_productWeightUnit = ProductMeasurementUnit.weightFromCode(
|
||||||
|
resp.productWeightUnit,
|
||||||
|
);
|
||||||
_allowNegativeInventoryForUnique = resp.allowNegativeInventoryForUnique;
|
_allowNegativeInventoryForUnique = resp.allowNegativeInventoryForUnique;
|
||||||
_warehouseTransferRequirePositiveStock = resp.warehouseTransferRequirePositiveStock;
|
_warehouseTransferRequirePositiveStock = resp.warehouseTransferRequirePositiveStock;
|
||||||
_geiWorkflowMode = resp.goodsExpenseIncomeWorkflowMode;
|
_geiWorkflowMode = resp.goodsExpenseIncomeWorkflowMode;
|
||||||
|
|
@ -433,6 +442,12 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
if (_allowNegativeInventoryForBulk != orig.allowNegativeInventoryForBulk) {
|
if (_allowNegativeInventoryForBulk != orig.allowNegativeInventoryForBulk) {
|
||||||
payload['allow_negative_inventory_for_bulk'] = _allowNegativeInventoryForBulk;
|
payload['allow_negative_inventory_for_bulk'] = _allowNegativeInventoryForBulk;
|
||||||
}
|
}
|
||||||
|
if (_productDimensionUnit.code != orig.productDimensionUnit) {
|
||||||
|
payload['product_dimension_unit'] = _productDimensionUnit.code;
|
||||||
|
}
|
||||||
|
if (_productWeightUnit.code != orig.productWeightUnit) {
|
||||||
|
payload['product_weight_unit'] = _productWeightUnit.code;
|
||||||
|
}
|
||||||
if (_allowNegativeInventoryForUnique != orig.allowNegativeInventoryForUnique) {
|
if (_allowNegativeInventoryForUnique != orig.allowNegativeInventoryForUnique) {
|
||||||
payload['allow_negative_inventory_for_unique'] = _allowNegativeInventoryForUnique;
|
payload['allow_negative_inventory_for_unique'] = _allowNegativeInventoryForUnique;
|
||||||
}
|
}
|
||||||
|
|
@ -1296,6 +1311,23 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
_buildInventoryNegativePolicySettings(cs),
|
_buildInventoryNegativePolicySettings(cs),
|
||||||
|
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
_buildSectionTitle('واحدهای مشخصات فیزیکی کالا', cs),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
_measurementUnitDropdown(
|
||||||
|
'واحد ابعاد کالا',
|
||||||
|
_productDimensionUnit,
|
||||||
|
ProductMeasurementUnit.dimensionUnits,
|
||||||
|
(unit) => setState(() => _productDimensionUnit = unit),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_measurementUnitDropdown(
|
||||||
|
'واحد وزن کالا',
|
||||||
|
_productWeightUnit,
|
||||||
|
ProductMeasurementUnit.weightUnits,
|
||||||
|
(unit) => setState(() => _productWeightUnit = unit),
|
||||||
|
),
|
||||||
|
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
_buildSectionTitle('کالای هزینهشده / کالای درآمدشده', cs),
|
_buildSectionTitle('کالای هزینهشده / کالای درآمدشده', cs),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
|
|
@ -1697,6 +1729,25 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
Widget _measurementUnitDropdown(
|
||||||
|
String label,
|
||||||
|
ProductMeasurementUnit selected,
|
||||||
|
List<ProductMeasurementUnit> units,
|
||||||
|
ValueChanged<ProductMeasurementUnit> onChanged,
|
||||||
|
) {
|
||||||
|
return DropdownButtonFormField<ProductMeasurementUnit>(
|
||||||
|
initialValue: selected,
|
||||||
|
decoration: InputDecoration(labelText: label),
|
||||||
|
items: [
|
||||||
|
for (final unit in units)
|
||||||
|
DropdownMenuItem(value: unit, child: Text(unit.label)),
|
||||||
|
],
|
||||||
|
onChanged: _saving ? null : (unit) {
|
||||||
|
if (unit != null) onChanged(unit);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Widget _buildInventoryNegativePolicySettings(ColorScheme cs) {
|
Widget _buildInventoryNegativePolicySettings(ColorScheme cs) {
|
||||||
final t = AppLocalizations.of(context);
|
final t = AppLocalizations.of(context);
|
||||||
return Card(
|
return Card(
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,8 @@ import '../../widgets/data_table/data_table_config.dart';
|
||||||
import '../../widgets/product/product_form_dialog.dart';
|
import '../../widgets/product/product_form_dialog.dart';
|
||||||
import '../../widgets/product/product_list_category_filter_bar.dart';
|
import '../../widgets/product/product_list_category_filter_bar.dart';
|
||||||
import '../../widgets/product/category_tree_widget.dart';
|
import '../../widgets/product/category_tree_widget.dart';
|
||||||
|
import '../../models/product_measurement.dart';
|
||||||
|
import '../../services/business_api_service.dart';
|
||||||
import '../../services/category_service.dart';
|
import '../../services/category_service.dart';
|
||||||
import '../../services/list_filter_preferences_service.dart';
|
import '../../services/list_filter_preferences_service.dart';
|
||||||
import '../../services/report_template_service.dart';
|
import '../../services/report_template_service.dart';
|
||||||
|
|
@ -34,6 +36,7 @@ import '../../utils/number_formatters.dart';
|
||||||
import '../../utils/date_formatters.dart';
|
import '../../utils/date_formatters.dart';
|
||||||
import '../../services/warehouse_service.dart';
|
import '../../services/warehouse_service.dart';
|
||||||
import '../../services/price_list_service.dart';
|
import '../../services/price_list_service.dart';
|
||||||
|
import '../../services/product_service.dart';
|
||||||
import '../../utils/image_cache.dart';
|
import '../../utils/image_cache.dart';
|
||||||
import 'price_lists_page.dart';
|
import 'price_lists_page.dart';
|
||||||
import '../../utils/snackbar_helper.dart';
|
import '../../utils/snackbar_helper.dart';
|
||||||
|
|
@ -60,11 +63,13 @@ class _InfoTileData {
|
||||||
final String label;
|
final String label;
|
||||||
final String value;
|
final String value;
|
||||||
final IconData icon;
|
final IconData icon;
|
||||||
|
final bool fitValue;
|
||||||
|
|
||||||
const _InfoTileData({
|
const _InfoTileData({
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.value,
|
required this.value,
|
||||||
required this.icon,
|
required this.icon,
|
||||||
|
this.fitValue = false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -591,6 +596,12 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
final valueStyle = isMobile
|
final valueStyle = isMobile
|
||||||
? theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600)
|
? theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600)
|
||||||
: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600);
|
: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600);
|
||||||
|
final value = Text(
|
||||||
|
item.value.isEmpty ? '-' : item.value,
|
||||||
|
style: valueStyle,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
);
|
||||||
return Container(
|
return Container(
|
||||||
padding: EdgeInsets.all(tilePad),
|
padding: EdgeInsets.all(tilePad),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
|
|
@ -621,12 +632,8 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
SizedBox(height: isMobile ? 4 : 8),
|
SizedBox(height: isMobile ? 4 : 8),
|
||||||
Text(
|
if (item.fitValue) FittedBox(fit: BoxFit.scaleDown, child: value)
|
||||||
item.value.isEmpty ? '-' : item.value,
|
else value,
|
||||||
style: valueStyle,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
@ -772,6 +779,7 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
required String serviceType,
|
required String serviceType,
|
||||||
required String barcode,
|
required String barcode,
|
||||||
required AppLocalizations t,
|
required AppLocalizations t,
|
||||||
|
required Future<List<_InfoTileData>>? measurements,
|
||||||
}) {
|
}) {
|
||||||
final theme = Theme.of(dialogContext);
|
final theme = Theme.of(dialogContext);
|
||||||
final generalItems = [
|
final generalItems = [
|
||||||
|
|
@ -823,6 +831,24 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
builder: (context, constraints) {
|
builder: (context, constraints) {
|
||||||
final isMobile = ResponsiveHelper.isMobile(context);
|
final isMobile = ResponsiveHelper.isMobile(context);
|
||||||
final generalFooter = <Widget>[
|
final generalFooter = <Widget>[
|
||||||
|
if (measurements != null) ...[
|
||||||
|
SizedBox(height: sectionGap),
|
||||||
|
Text('مشخصات فیزیکی', style: theme.textTheme.labelLarge),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
FutureBuilder<List<_InfoTileData>>(
|
||||||
|
future: measurements,
|
||||||
|
builder: (context, snapshot) {
|
||||||
|
final items = snapshot.data;
|
||||||
|
if (items != null) {
|
||||||
|
return _buildInfoGrid(theme, items, context);
|
||||||
|
}
|
||||||
|
if (snapshot.hasError) {
|
||||||
|
return const Text('مشخصات فیزیکی کالا دریافت نشد.');
|
||||||
|
}
|
||||||
|
return const LinearProgressIndicator();
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
SizedBox(height: overviewCompact ? 10 : 12),
|
SizedBox(height: overviewCompact ? 10 : 12),
|
||||||
Text(
|
Text(
|
||||||
t.productGeneralBarcodes,
|
t.productGeneralBarcodes,
|
||||||
|
|
@ -1162,6 +1188,33 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<List<_InfoTileData>> _loadProductMeasurements(int productId) async {
|
||||||
|
final (product, business) = await (
|
||||||
|
ProductService().getProduct(businessId: widget.businessId, productId: productId),
|
||||||
|
BusinessApiService.getBusiness(widget.businessId),
|
||||||
|
).wait;
|
||||||
|
if (product.isEmpty) throw StateError('Could not load product details.');
|
||||||
|
|
||||||
|
final dimension = ProductMeasurementUnit.dimensionFromCode(business.productDimensionUnit);
|
||||||
|
final weight = ProductMeasurementUnit.weightFromCode(business.productWeightUnit);
|
||||||
|
return ProductMeasurement.values.map((field) {
|
||||||
|
final unit = field == ProductMeasurement.weight ? weight : dimension;
|
||||||
|
final display = unit.format(product[field.apiKey] as String?);
|
||||||
|
final prefix = display.approximate ? '≈ ' : '';
|
||||||
|
return _InfoTileData(
|
||||||
|
label: field.label,
|
||||||
|
value: display.value.isEmpty ? '' : '$prefix${display.value} ${unit.label}',
|
||||||
|
icon: switch (field) {
|
||||||
|
ProductMeasurement.length => Icons.straighten,
|
||||||
|
ProductMeasurement.width => Icons.swap_horiz,
|
||||||
|
ProductMeasurement.height => Icons.swap_vert,
|
||||||
|
ProductMeasurement.weight => Icons.scale_outlined,
|
||||||
|
},
|
||||||
|
fitValue: true,
|
||||||
|
);
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _showProductDetailsDialog(Map<String, dynamic> product) async {
|
Future<void> _showProductDetailsDialog(Map<String, dynamic> product) async {
|
||||||
final t = AppLocalizations.of(context);
|
final t = AppLocalizations.of(context);
|
||||||
// در صورت وجود thumbnail، میتوان از آن برای پیشنمایش استفاده کرد؛ در غیر این صورت تصویر اصلی
|
// در صورت وجود thumbnail، میتوان از آن برای پیشنمایش استفاده کرد؛ در غیر این صورت تصویر اصلی
|
||||||
|
|
@ -1170,6 +1223,13 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
);
|
);
|
||||||
final attachmentsKey = AttachedFilesWidgetKey();
|
final attachmentsKey = AttachedFilesWidgetKey();
|
||||||
bool uploadingFile = false;
|
bool uploadingFile = false;
|
||||||
|
final productId = product['id'];
|
||||||
|
final parsedProductId = productId is int
|
||||||
|
? productId
|
||||||
|
: (productId is num ? productId.toInt() : int.tryParse(productId?.toString() ?? ''));
|
||||||
|
late final measurements = parsedProductId != null && product['item_type'] == 'کالا'
|
||||||
|
? _loadProductMeasurements(parsedProductId)
|
||||||
|
: null;
|
||||||
|
|
||||||
await showDialog<void>(
|
await showDialog<void>(
|
||||||
context: context,
|
context: context,
|
||||||
|
|
@ -1184,10 +1244,6 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
final tracking = product['track_inventory'] == true ? t.yes : t.no;
|
final tracking = product['track_inventory'] == true ? t.yes : t.no;
|
||||||
final serviceType = _stringValue(product['item_type']);
|
final serviceType = _stringValue(product['item_type']);
|
||||||
final barcode = _stringValue(product['barcode']);
|
final barcode = _stringValue(product['barcode']);
|
||||||
final productId = product['id'];
|
|
||||||
final parsedProductId = productId is int
|
|
||||||
? productId
|
|
||||||
: (productId is num ? productId.toInt() : int.tryParse(productId?.toString() ?? ''));
|
|
||||||
final tabRules = _ProductDetailsTabRules.resolve(
|
final tabRules = _ProductDetailsTabRules.resolve(
|
||||||
product: product,
|
product: product,
|
||||||
parsedProductId: parsedProductId,
|
parsedProductId: parsedProductId,
|
||||||
|
|
@ -1343,6 +1399,7 @@ class _ProductsPageState extends State<ProductsPage> {
|
||||||
serviceType: serviceType,
|
serviceType: serviceType,
|
||||||
barcode: barcode,
|
barcode: barcode,
|
||||||
t: t,
|
t: t,
|
||||||
|
measurements: measurements,
|
||||||
),
|
),
|
||||||
if (tabRules.showInstancesTab)
|
if (tabRules.showInstancesTab)
|
||||||
ProductUniqueInstancesTab(
|
ProductUniqueInstancesTab(
|
||||||
|
|
|
||||||
|
|
@ -152,8 +152,11 @@ class BusinessApiService {
|
||||||
}
|
}
|
||||||
|
|
||||||
// دریافت جزئیات یک کسب و کار
|
// دریافت جزئیات یک کسب و کار
|
||||||
static Future<BusinessResponse> getBusiness(int businessId) async {
|
static Future<BusinessResponse> getBusiness(
|
||||||
final response = await _apiClient.get('$_basePath/$businessId');
|
int businessId, {
|
||||||
|
ApiClient? apiClient,
|
||||||
|
}) async {
|
||||||
|
final response = await (apiClient ?? _apiClient).get('$_basePath/$businessId');
|
||||||
|
|
||||||
if (response.data['success'] == true) {
|
if (response.data['success'] == true) {
|
||||||
return BusinessResponse.fromJson(response.data['data']);
|
return BusinessResponse.fromJson(response.data['data']);
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import '../models/product_form_data.dart';
|
import '../models/product_form_data.dart';
|
||||||
|
import '../models/product_measurement.dart';
|
||||||
|
|
||||||
/// سرویس برای ذخیره و بارگذاری خودکار فرم کالا
|
/// سرویس برای ذخیره و بارگذاری خودکار فرم کالا
|
||||||
class ProductFormAutoSave {
|
class ProductFormAutoSave {
|
||||||
|
|
@ -44,6 +45,8 @@ class ProductFormAutoSave {
|
||||||
'description': formData.description,
|
'description': formData.description,
|
||||||
'generalBarcodes': formData.generalBarcodes,
|
'generalBarcodes': formData.generalBarcodes,
|
||||||
'categoryId': formData.categoryId,
|
'categoryId': formData.categoryId,
|
||||||
|
for (final entry in formData.physicalMeasurements.entries)
|
||||||
|
entry.key.apiKey: entry.value,
|
||||||
'trackInventory': formData.trackInventory,
|
'trackInventory': formData.trackInventory,
|
||||||
'reorderPoint': formData.reorderPoint,
|
'reorderPoint': formData.reorderPoint,
|
||||||
'minOrderQty': formData.minOrderQty,
|
'minOrderQty': formData.minOrderQty,
|
||||||
|
|
@ -113,6 +116,10 @@ class ProductFormAutoSave {
|
||||||
description: data['description'] as String?,
|
description: data['description'] as String?,
|
||||||
generalBarcodes: data['generalBarcodes'] as String?,
|
generalBarcodes: data['generalBarcodes'] as String?,
|
||||||
categoryId: data['categoryId'] as int?,
|
categoryId: data['categoryId'] as int?,
|
||||||
|
physicalMeasurements: {
|
||||||
|
for (final field in ProductMeasurement.values)
|
||||||
|
field: data[field.apiKey] as String?,
|
||||||
|
},
|
||||||
trackInventory: data['trackInventory'] as bool? ?? false,
|
trackInventory: data['trackInventory'] as bool? ?? false,
|
||||||
reorderPoint: data['reorderPoint'] as int?,
|
reorderPoint: data['reorderPoint'] as int?,
|
||||||
minOrderQty: data['minOrderQty'] as int?,
|
minOrderQty: data['minOrderQty'] as int?,
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import 'package:hesabix_ui/l10n/app_localizations.dart';
|
||||||
|
|
||||||
import '../../category/category_picker_field.dart';
|
import '../../category/category_picker_field.dart';
|
||||||
import '../../../models/product_form_data.dart';
|
import '../../../models/product_form_data.dart';
|
||||||
|
import '../../../models/product_measurement.dart';
|
||||||
import '../../../utils/number_normalizer.dart';
|
import '../../../utils/number_normalizer.dart';
|
||||||
import '../../../utils/product_form_validator.dart';
|
import '../../../utils/product_form_validator.dart';
|
||||||
import '../../../controllers/product_form_controller.dart';
|
import '../../../controllers/product_form_controller.dart';
|
||||||
|
|
@ -291,6 +292,12 @@ class _ProductBasicInfoSectionState extends State<ProductBasicInfoSection> {
|
||||||
SizedBox(height: spacing),
|
SizedBox(height: spacing),
|
||||||
_buildUnitsSection(context),
|
_buildUnitsSection(context),
|
||||||
],
|
],
|
||||||
|
if (widget.formData.itemType == 'کالا' && widget.controller != null) ...[
|
||||||
|
SizedBox(height: spacing * 2),
|
||||||
|
Text('مشخصات فیزیکی', style: Theme.of(context).textTheme.titleSmall),
|
||||||
|
SizedBox(height: spacing),
|
||||||
|
_buildMeasurements(widget.controller!, spacing),
|
||||||
|
],
|
||||||
if (widget.productId != null) ...[
|
if (widget.productId != null) ...[
|
||||||
SizedBox(height: spacing),
|
SizedBox(height: spacing),
|
||||||
QuickSalesPersonalPinToggle(
|
QuickSalesPersonalPinToggle(
|
||||||
|
|
@ -348,6 +355,51 @@ class _ProductBasicInfoSectionState extends State<ProductBasicInfoSection> {
|
||||||
widget.onChanged(newData);
|
widget.onChanged(newData);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Widget _buildMeasurements(ProductFormController controller, double spacing) {
|
||||||
|
if (controller.measurementUnit(ProductMeasurement.length) == null) {
|
||||||
|
return const Text('واحدهای کالا دریافت نشد. برای ورود اندازهها فرم را دوباره باز کنید.');
|
||||||
|
}
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final columns = constraints.maxWidth >= 520 ? 2 : 1;
|
||||||
|
final width = (constraints.maxWidth - (columns - 1) * spacing) / columns;
|
||||||
|
return Wrap(
|
||||||
|
spacing: spacing,
|
||||||
|
runSpacing: spacing,
|
||||||
|
children: [
|
||||||
|
for (final field in ProductMeasurement.values)
|
||||||
|
SizedBox(
|
||||||
|
width: width,
|
||||||
|
child: _measurementField(controller, field),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _measurementField(
|
||||||
|
ProductFormController controller,
|
||||||
|
ProductMeasurement field,
|
||||||
|
) {
|
||||||
|
final unit = controller.measurementUnit(field)!;
|
||||||
|
return TextFormField(
|
||||||
|
key: ValueKey(field.apiKey),
|
||||||
|
initialValue: controller.measurementInput(field),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
labelText: '${field.label} (${unit.label})',
|
||||||
|
helperText: controller.isMeasurementApproximate(field)
|
||||||
|
? 'نمایش تقریبی'
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
textDirection: TextDirection.ltr,
|
||||||
|
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||||
|
inputFormatters: const [EnglishDigitsFormatter()],
|
||||||
|
onChanged: (value) => controller.updateMeasurement(field, value),
|
||||||
|
validator: (value) => controller.measurementError(field, value ?? ''),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Widget _buildProductCodeBlock(BuildContext context, double spacing) {
|
Widget _buildProductCodeBlock(BuildContext context, double spacing) {
|
||||||
final t = AppLocalizations.of(context);
|
final t = AppLocalizations.of(context);
|
||||||
final editing = widget.controller?.isEditingProduct == true;
|
final editing = widget.controller?.isEditingProduct == true;
|
||||||
|
|
|
||||||
316
hesabixUI/hesabix_ui/test/product_measurement_dialog_test.dart
Normal file
316
hesabixUI/hesabix_ui/test/product_measurement_dialog_test.dart
Normal file
|
|
@ -0,0 +1,316 @@
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:go_router/go_router.dart';
|
||||||
|
import 'package:hesabix_ui/core/api_client.dart';
|
||||||
|
import 'package:hesabix_ui/core/auth_store.dart';
|
||||||
|
import 'package:hesabix_ui/l10n/app_localizations.dart';
|
||||||
|
import 'package:hesabix_ui/models/business_dashboard_models.dart';
|
||||||
|
import 'package:hesabix_ui/models/product_measurement.dart';
|
||||||
|
import 'package:hesabix_ui/pages/business/business_info_settings_page.dart';
|
||||||
|
import 'package:hesabix_ui/pages/business/products_page.dart';
|
||||||
|
import 'package:hesabix_ui/widgets/product/product_form_dialog.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets(
|
||||||
|
'product forms and read-only details use exact measurements across units',
|
||||||
|
(tester) async {
|
||||||
|
final originalHttpOverrides = HttpOverrides.current;
|
||||||
|
HttpOverrides.global = null;
|
||||||
|
addTearDown(() => HttpOverrides.global = originalHttpOverrides);
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
FlutterSecureStorage.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(1280, 960);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final auth = AuthStore();
|
||||||
|
ApiClient.bindAuthStore(auth);
|
||||||
|
final client = ApiClient();
|
||||||
|
await tester.runAsync(() => auth.saveApiKey('measurement-fixture-1'));
|
||||||
|
|
||||||
|
Future<void> units(String dimension, String weight) async {
|
||||||
|
await tester.runAsync(
|
||||||
|
() => client.put(
|
||||||
|
'/api/v1/businesses/1',
|
||||||
|
data: {
|
||||||
|
'product_dimension_unit': dimension,
|
||||||
|
'product_weight_unit': weight,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> waitFor(bool Function() condition) async {
|
||||||
|
for (var attempt = 0; attempt < 400; attempt++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 30));
|
||||||
|
if (condition()) break;
|
||||||
|
await tester.runAsync(
|
||||||
|
() => Future<void>.delayed(const Duration(milliseconds: 35)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(condition(), isTrue);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
|
||||||
|
var productId = 0;
|
||||||
|
final router = GoRouter(
|
||||||
|
initialLocation: '/business/1/settings',
|
||||||
|
routes: [
|
||||||
|
GoRoute(
|
||||||
|
path: '/business/1/settings',
|
||||||
|
builder: (context, _) => Scaffold(
|
||||||
|
body: Column(
|
||||||
|
children: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
final id = await showDialog<Object>(
|
||||||
|
context: context,
|
||||||
|
builder: (_) => ProductFormDialog(
|
||||||
|
businessId: 1,
|
||||||
|
authStore: auth,
|
||||||
|
product: productId == 0 ? null : {'id': productId},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (id is int) productId = id;
|
||||||
|
},
|
||||||
|
child: const Text('Open product'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => context.go('/business/1/business-info'),
|
||||||
|
child: const Text('Open settings'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
GoRoute(
|
||||||
|
path: '/business/1/business-info',
|
||||||
|
builder: (_, _) => const BusinessInfoSettingsPage(businessId: 1),
|
||||||
|
),
|
||||||
|
GoRoute(
|
||||||
|
path: '/business/1/products',
|
||||||
|
builder: (_, _) => ProductsPage(businessId: 1, authStore: auth),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
addTearDown(router.dispose);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp.router(
|
||||||
|
routerConfig: router,
|
||||||
|
locale: const Locale('fa'),
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
const keys = ['length_mm', 'width_mm', 'height_mm', 'weight_g'];
|
||||||
|
Finder field(String key) => find.byKey(ValueKey(key));
|
||||||
|
String read(String key) => tester
|
||||||
|
.widget<EditableText>(
|
||||||
|
find.descendant(
|
||||||
|
of: field(key),
|
||||||
|
matching: find.byType(EditableText),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.controller
|
||||||
|
.text;
|
||||||
|
|
||||||
|
Future<void> enter(Finder field, String value) async {
|
||||||
|
await tester.ensureVisible(field);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.enterText(field, value);
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> open() async {
|
||||||
|
await tester.tap(find.text('Open product'));
|
||||||
|
await waitFor(() => field('length_mm').evaluate().isNotEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> save() async {
|
||||||
|
await tester.tap(find.widgetWithText(FilledButton, 'ذخیره'));
|
||||||
|
await waitFor(() => find.byType(ProductFormDialog).evaluate().isEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> dismiss() async {
|
||||||
|
await tester.tapAt(const Offset(4, 4));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(ProductFormDialog), findsNothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> chooseUnitsInSettings(
|
||||||
|
ProductMeasurementUnit dimension,
|
||||||
|
ProductMeasurementUnit weight,
|
||||||
|
) async {
|
||||||
|
await tester.tap(find.text('Open settings'));
|
||||||
|
final dropdowns = find.byWidgetPredicate(
|
||||||
|
(widget) => widget is DropdownButtonFormField<ProductMeasurementUnit>,
|
||||||
|
);
|
||||||
|
await waitFor(() => dropdowns.evaluate().length == 2);
|
||||||
|
for (final (index, unit) in [dimension, weight].indexed) {
|
||||||
|
final field = dropdowns.at(index);
|
||||||
|
await tester.ensureVisible(field);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(field);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text(unit.label).last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
final save = find.ancestor(
|
||||||
|
of: find.text('ذخیره'),
|
||||||
|
matching: find.byWidgetPredicate((widget) => widget is FilledButton),
|
||||||
|
);
|
||||||
|
await tester.ensureVisible(save);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(save);
|
||||||
|
await waitFor(() => find.text('Open product').evaluate().isNotEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
|
void expectValues(List<String> expected) {
|
||||||
|
expect(keys.map(read).toList(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
final title = find.byWidgetPredicate(
|
||||||
|
(widget) =>
|
||||||
|
widget is TextField && widget.decoration?.labelText == 'عنوان',
|
||||||
|
);
|
||||||
|
await units('mm', 'g');
|
||||||
|
await open();
|
||||||
|
expectValues(['', '', '', '']);
|
||||||
|
await enter(title, 'UI physical product');
|
||||||
|
await enter(field('length_mm'), '-1');
|
||||||
|
await tester.tap(find.widgetWithText(FilledButton, 'ذخیره'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('عدد صحیح یا اعشاری غیرمنفی وارد کنید.'), findsWidgets);
|
||||||
|
const entered = ['125.5', '22.375', '3.0625', '1250.5'];
|
||||||
|
for (var index = 0; index < keys.length; index++) {
|
||||||
|
await enter(field(keys[index]), entered[index]);
|
||||||
|
}
|
||||||
|
await save();
|
||||||
|
expect(productId, greaterThan(0));
|
||||||
|
|
||||||
|
await open();
|
||||||
|
expectValues(entered);
|
||||||
|
await enter(field('width_mm'), '22.8125');
|
||||||
|
await save();
|
||||||
|
|
||||||
|
await chooseUnitsInSettings(
|
||||||
|
ProductMeasurementUnit.cm,
|
||||||
|
ProductMeasurementUnit.kg,
|
||||||
|
);
|
||||||
|
await open();
|
||||||
|
expectValues(['12.55', '2.28125', '0.30625', '1.2505']);
|
||||||
|
await enter(field('height_mm'), '0.3125');
|
||||||
|
await enter(field('weight_g'), '1.250625');
|
||||||
|
await units('m', 't');
|
||||||
|
expectValues(['12.55', '2.28125', '0.3125', '1.250625']);
|
||||||
|
await save();
|
||||||
|
|
||||||
|
await open();
|
||||||
|
expectValues(['0.1255', '0.0228125', '0.003125', '0.001250625']);
|
||||||
|
final productName = 'UI physical product edited $productId';
|
||||||
|
await enter(title, productName);
|
||||||
|
await save();
|
||||||
|
|
||||||
|
await chooseUnitsInSettings(
|
||||||
|
ProductMeasurementUnit.mm,
|
||||||
|
ProductMeasurementUnit.g,
|
||||||
|
);
|
||||||
|
await open();
|
||||||
|
expectValues(['125.5', '22.8125', '3.125', '1250.625']);
|
||||||
|
await dismiss();
|
||||||
|
|
||||||
|
await units('m', 't');
|
||||||
|
await open();
|
||||||
|
await enter(field('height_mm'), '0.0031875');
|
||||||
|
await enter(field('weight_g'), '0.00125075');
|
||||||
|
await save();
|
||||||
|
await units('mm', 'g');
|
||||||
|
await open();
|
||||||
|
expectValues(['125.5', '22.8125', '3.1875', '1250.75']);
|
||||||
|
await dismiss();
|
||||||
|
|
||||||
|
await tester.runAsync(() async {
|
||||||
|
final response = await client.get('/api/v1/businesses/1');
|
||||||
|
await auth.setCurrentBusiness(
|
||||||
|
BusinessWithPermission.fromJson({
|
||||||
|
...Map<String, dynamic>.from(response.data['data'] as Map),
|
||||||
|
'is_owner': true,
|
||||||
|
'role': 'owner',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await units('cm', 'kg');
|
||||||
|
router.go('/business/1/products');
|
||||||
|
final row = find.text(productName);
|
||||||
|
await waitFor(() => row.evaluate().isNotEmpty);
|
||||||
|
await tester.ensureVisible(row);
|
||||||
|
await tester.tap(row);
|
||||||
|
await waitFor(() => find.text('1.25075 کیلوگرم').evaluate().isNotEmpty);
|
||||||
|
expect(find.text('12.55 سانتیمتر'), findsOneWidget);
|
||||||
|
expect(find.text('2.28125 سانتیمتر'), findsOneWidget);
|
||||||
|
expect(find.text('0.31875 سانتیمتر'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tapAt(const Offset(4, 4));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await units('mm', 'g');
|
||||||
|
await tester.ensureVisible(row);
|
||||||
|
await tester.tap(row);
|
||||||
|
await waitFor(() => find.text('1250.75 گرم').evaluate().isNotEmpty);
|
||||||
|
expect(find.text('125.5 میلیمتر'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tapAt(const Offset(4, 4));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
router.go('/business/1/settings');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await chooseUnitsInSettings(
|
||||||
|
ProductMeasurementUnit.inch,
|
||||||
|
ProductMeasurementUnit.oz,
|
||||||
|
);
|
||||||
|
await open();
|
||||||
|
expect(find.text('نمایش تقریبی'), findsWidgets);
|
||||||
|
// A re-entered approximation and an unrelated title edit keep the stored length.
|
||||||
|
await enter(field('length_mm'), '${read('length_mm')}0');
|
||||||
|
final imperialProductName = '$productName imperial';
|
||||||
|
await enter(title, imperialProductName);
|
||||||
|
await enter(field('weight_g'), '1.234567');
|
||||||
|
await save();
|
||||||
|
|
||||||
|
await open();
|
||||||
|
expect(read('weight_g'), '1.234567');
|
||||||
|
await dismiss();
|
||||||
|
router.go('/business/1/products');
|
||||||
|
final imperialRow = find.text(imperialProductName);
|
||||||
|
await waitFor(() => imperialRow.evaluate().isNotEmpty);
|
||||||
|
await tester.ensureVisible(imperialRow);
|
||||||
|
await tester.tap(imperialRow);
|
||||||
|
await waitFor(() => find.text('1.234567 اونس').evaluate().isNotEmpty);
|
||||||
|
expect(
|
||||||
|
find.text('≈ ${ProductMeasurementUnit.inch.display('125.5')} اینچ'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tapAt(const Offset(4, 4));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await units('mm', 'g');
|
||||||
|
router.go('/business/1/settings');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await open();
|
||||||
|
expectValues(['125.5', '22.8125', '3.1875', '34.999385715861875']);
|
||||||
|
await dismiss();
|
||||||
|
|
||||||
|
await tester.pumpWidget(const SizedBox.shrink());
|
||||||
|
// Let Dart's HTTP keep-alive timers expire on the widget test clock.
|
||||||
|
await tester.pump(const Duration(seconds: 4));
|
||||||
|
},
|
||||||
|
skip: !const bool.fromEnvironment(
|
||||||
|
'HESABIX_TEST_PRODUCT_MEASUREMENT_DIALOG',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
87
hesabixUI/hesabix_ui/test/product_measurement_test.dart
Normal file
87
hesabixUI/hesabix_ui/test/product_measurement_test.dart
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:hesabix_ui/models/product_measurement.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('each display unit converts both ways without rounding', () {
|
||||||
|
const cases = [
|
||||||
|
(ProductMeasurementUnit.um, '0.1255', '125.5'),
|
||||||
|
(ProductMeasurementUnit.mm, '125.5', '125.5'),
|
||||||
|
(ProductMeasurementUnit.cm, '125.5', '12.55'),
|
||||||
|
(ProductMeasurementUnit.dm, '125.5', '1.255'),
|
||||||
|
(ProductMeasurementUnit.m, '125.5', '0.1255'),
|
||||||
|
(ProductMeasurementUnit.km, '125.5', '0.0001255'),
|
||||||
|
(ProductMeasurementUnit.inch, '31.3580018', '1.234567'),
|
||||||
|
(ProductMeasurementUnit.ft, '457.2', '1.5'),
|
||||||
|
(ProductMeasurementUnit.yd, '1371.6', '1.5'),
|
||||||
|
(ProductMeasurementUnit.mi, '402336', '0.25'),
|
||||||
|
(ProductMeasurementUnit.ug, '0.0012505', '1250.5'),
|
||||||
|
(ProductMeasurementUnit.mg, '1.2505', '1250.5'),
|
||||||
|
(ProductMeasurementUnit.g, '1250.5', '1250.5'),
|
||||||
|
(ProductMeasurementUnit.kg, '1250.5', '1.2505'),
|
||||||
|
(ProductMeasurementUnit.t, '1250.5', '0.0012505'),
|
||||||
|
(ProductMeasurementUnit.oz, '34.999385715861875', '1.234567'),
|
||||||
|
(ProductMeasurementUnit.lb, '559.99017145379', '1.234567'),
|
||||||
|
];
|
||||||
|
for (final (unit, base, entered) in cases) {
|
||||||
|
expect(unit.format(base), (value: entered, approximate: false));
|
||||||
|
expect(unit.toBaseValue(entered), base);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the storage limits follow the unit and significant decimal places', () {
|
||||||
|
for (final unit in ProductMeasurementUnit.values) {
|
||||||
|
for (final base in [
|
||||||
|
'0.000000000000001',
|
||||||
|
'999999999999.999999999999999',
|
||||||
|
]) {
|
||||||
|
final display = unit.format(base);
|
||||||
|
expect(display.value, isNot('0'));
|
||||||
|
expect(unit.toBaseValue(display.value, original: base), base);
|
||||||
|
if (!display.approximate) expect(unit.toBaseValue(display.value), base);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(ProductMeasurementUnit.t.toBaseValue('.000000000001'), '0.000001');
|
||||||
|
expect(ProductMeasurementUnit.mm.toBaseValue(' ۱۲۵٫۵۰۰۰۰۰۰۰ '), '125.5');
|
||||||
|
expect(ProductMeasurementUnit.g.toBaseValue(''), isNull);
|
||||||
|
expect(ProductMeasurementUnit.g.toBaseValue('0'), '0');
|
||||||
|
for (final input in [
|
||||||
|
'-1',
|
||||||
|
'-0',
|
||||||
|
'1.2.3',
|
||||||
|
'NaN',
|
||||||
|
'1e2',
|
||||||
|
'abc',
|
||||||
|
'1,500',
|
||||||
|
'1000000000000',
|
||||||
|
'0.0000000000000001',
|
||||||
|
]) {
|
||||||
|
expect(
|
||||||
|
() => ProductMeasurementUnit.g.toBaseValue(input),
|
||||||
|
throwsFormatException,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'a recurring imperial display preserves the original until the input changes',
|
||||||
|
() {
|
||||||
|
const unit = ProductMeasurementUnit.inch;
|
||||||
|
const base = '125.500000000000000';
|
||||||
|
final approximate = unit.format(base);
|
||||||
|
expect(approximate.approximate, isTrue);
|
||||||
|
expect(unit.toBaseValue(approximate.value, original: base), base);
|
||||||
|
expect(unit.toBaseValue('${approximate.value}0', original: base), base);
|
||||||
|
expect(unit.toBaseValue('5', original: base), '127');
|
||||||
|
expect(unit.toBaseValue('', original: base), isNull);
|
||||||
|
expect(ProductMeasurementUnit.dimensionFromCode('in'), unit);
|
||||||
|
expect(
|
||||||
|
() => ProductMeasurementUnit.oz.toBaseValue('1.2345671'),
|
||||||
|
throwsFormatException,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
ProductMeasurementUnit.oz.toBaseValue('1.2345678'),
|
||||||
|
'34.999408395480375',
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue