From 8ec908bbd1c3a30f7cdac99ddc3e43898f7d0dad Mon Sep 17 00:00:00 2001 From: Mohammad Date: Sat, 17 Oct 2026 20:53:41 +0330 Subject: [PATCH] fix(quick-sales): harden invoice and payment workflows --- .../QUICK_SALES_AUDIT_HARDENING_2026-10-17.md | 75 +++++++ hesabixAPI/adapters/api/v1/customers.py | 43 +++- hesabixAPI/adapters/api/v1/invoices.py | 31 +++ hesabixAPI/adapters/api/v1/quick_sales.py | 69 ++++--- .../services/customer_quick_entry_service.py | 56 ++++++ .../services/inventory_discrepancy_service.py | 7 +- hesabixAPI/app/services/invoice_service.py | 133 ++++++++++++- .../app/services/quick_sales_service.py | 188 +++++++++--------- ...17_000001_quick_sales_audit_permissions.py | 68 +++++++ .../test_customer_quick_entry_service.py | 41 +++- .../tests/test_quick_sales_audit_hardening.py | 96 +++++++++ .../lib/models/quick_sales_parked_sale.dart | 33 ++- .../models/quick_sales_payment_button.dart | 3 + .../lib/pages/business/quick_sales_page.dart | 103 ++++++---- .../business/users_permissions_page.dart | 3 + .../lib/services/quick_sales_service.dart | 2 +- .../lib/utils/web/web_utils_stub.dart | 6 +- .../lib/utils/web/web_utils_web.dart | 14 ++ .../quick_sales/quick_sales_payment_dock.dart | 11 + .../test/quick_sales_parked_sale_test.dart | 14 ++ .../test/quick_sales_payment_dock_test.dart | 1 + 21 files changed, 821 insertions(+), 176 deletions(-) create mode 100644 docs/QUICK_SALES_AUDIT_HARDENING_2026-10-17.md create mode 100644 hesabixAPI/migrations/versions/20261017_000001_quick_sales_audit_permissions.py create mode 100644 hesabixAPI/tests/test_quick_sales_audit_hardening.py diff --git a/docs/QUICK_SALES_AUDIT_HARDENING_2026-10-17.md b/docs/QUICK_SALES_AUDIT_HARDENING_2026-10-17.md new file mode 100644 index 00000000..35d70c7a --- /dev/null +++ b/docs/QUICK_SALES_AUDIT_HARDENING_2026-10-17.md @@ -0,0 +1,75 @@ +# سخت‌سازی فروش سریع پس از ممیزی + +این سند تغییرات ممیزی فروش سریع در شاخه +`codex/quick-sales-audit-hardening` را برای بازبینی، استقرار و آزمون ثبت می‌کند. + +## ثبت فاکتور و مبالغ + +- هر تلاش ثبت فروش سریع یک `quick_sale_request_id` پایدار دارد. ارسال دوباره همان + درخواست، فاکتور قبلی را برمی‌گرداند و فاکتور دوم ایجاد نمی‌کند. +- یک ایندکس یکتای جزئی روی شناسه درخواست فروش سریع، آخرین لایه جلوگیری از ثبت + تکراری در درخواست‌های هم‌زمان است. +- جمع ردیف، تخفیف و مالیات ردیف در سرور از تعداد، قیمت، نوع/مقدار تخفیف و نرخ + مالیات دوباره محاسبه می‌شود. جمع‌های ارسالی رابط کاربری مرجع سند حسابداری نیستند. +- هنگام کنترل موجودی، برای ترکیب کالا و انبار قفل تراکنشی گرفته می‌شود تا دو فروش + هم‌زمان نتوانند از یک موجودی مشترک عبور کنند. +- مصرف مانده بستانکاری مشتری نیز با قفل شخص، ارز و سال مالی انجام می‌شود تا یک + اعتبار در دو صندوق هم‌زمان مصرف نشود. +- رسیدگی به پرونده کسری موجودی قفل تراکنشی دارد؛ در نتیجه دو درخواست هم‌زمان + نمی‌توانند دو سند اصلاح برای یک پرونده بسازند. + +## دسترسی و حریم اطلاعات مشتری + +سه مجوز مستقل به بخش `quick_sales` افزوده شده است: + +- `create_customer`: ثبت سریع مشتری +- `view_customer_contact`: جست‌وجو و مشاهده اطلاعات تماس مشتری +- `view_customer_balance`: مشاهده مانده حساب مشتری + +کاربری که مجوز متناظر در بخش اشخاص (`people.add` یا `people.view`) دارد نیز مجاز +است. migration برای کاربران فعلی دارای مجوز ثبت/ویرایش فاکتور، این سه دسترسی را +فعال می‌کند و مقدارهای صریح قبلی را تغییر نمی‌دهد. + +## مشتری ناشناس و تنظیمات + +- خواندن مشتری ناشناس دیگر داده‌ای در پایگاه داده ایجاد یا ویرایش نمی‌کند. +- ایجاد مشتری ناشناس فقط با `POST` و مجوز ثبت فاکتور انجام می‌شود. +- تنها شناسه ذخیره‌شده در تنظیمات، مشتری ناشناس را مشخص می‌کند؛ تشابه نام یک شخص + واقعی با عنوان «مشتری ناشناس» سبب انتخاب خودکار او نمی‌شود. +- ارز پیش‌فرض باید به کسب‌وکار تخصیص داده شده باشد. +- قالب چاپ باید منتشرشده، متعلق به همان کسب‌وکار و مربوط به فاکتورها باشد. + +## رابط کاربری + +- فروش‌های پارک‌شده بر اساس کسب‌وکار و کاربر جدا ذخیره می‌شوند. در وب، شناسه + `sessionStorage` هر زبانه نیز به کلید اضافه می‌شود تا دو زبانه داده یکدیگر را + بازنویسی نکنند. خطای ذخیره محلی فقط یک بار به کاربر اعلام می‌شود. +- فوکوس اولیه روی فیلد بارکد باقی می‌ماند. +- قیمت صفر در لیست قیمت معتبر است و با قیمت پایه جایگزین نمی‌شود. +- دکمه پرداخت صندوق یا بانک با ارز متفاوت از ارز فاکتور قابل استفاده نیست. +- از اجرای هم‌زمان چند ثبت جلوگیری می‌شود و شناسه فروش پارک‌شده همراه درخواست + فاکتور ارسال می‌گردد. +- نتیجه دقیق نام مشتری مستقل از سقف نتایج مشابه بررسی می‌شود. + +## migration و ترتیب استقرار + +migration جدید: + +`20261017_000001_quick_sales_audit_permissions` + +والد آن `20261015_000001_quick_sales_web_shortcut` است و یک head جدید موازی +نمی‌سازد. ترتیب استقرار پیشنهادی: اجرای migration، استقرار API، سپس انتشار رابط +کاربری است. API جدید برای فروش سریع، وجود `quick_sale_request_id` را الزامی می‌کند؛ +بنابراین رابط قدیمی نباید بعد از استقرار API برای ثبت فروش سریع استفاده شود. + +## آزمون پذیرش پیشنهادی + +1. یک فروش را با دوبار کلیک سریع روی ثبت ارسال کنید؛ فقط یک فاکتور باید ایجاد شود. +2. دو صندوق هم‌زمان آخرین موجودی یک کالا را بفروشند؛ یکی باید خطای کسری دریافت کند. +3. دو صندوق هم‌زمان مانده بستانکاری یک مشتری را اعمال کنند؛ درخواست دوم باید مانده + جدید را دریافت کند. +4. یک پرونده کسری را هم‌زمان در دو نشست اصلاح کنید؛ فقط یک سند اصلاح ساخته شود. +5. دسترسی‌های سه‌گانه مشتری را جداگانه خاموش و رفتار جست‌وجو، ثبت و مانده را بررسی + کنید. +6. یک قیمت صفر در لیست قیمت تعریف و ثبت مبلغ صفر همان ردیف را کنترل کنید. +7. دکمه پرداختی با ارز متفاوت بسازید؛ رابط باید پیش از افزودن پرداخت آن را رد کند. diff --git a/hesabixAPI/adapters/api/v1/customers.py b/hesabixAPI/adapters/api/v1/customers.py index bd27e948..d6c29b6b 100755 --- a/hesabixAPI/adapters/api/v1/customers.py +++ b/hesabixAPI/adapters/api/v1/customers.py @@ -7,6 +7,7 @@ from adapters.db.models.person import Person from adapters.db.session import get_db from app.core.responses import ApiError from app.core.auth_dependency import get_current_user, AuthContext +from app.core.permissions import has_business_permission_for_business from app.services.person_service import search_persons, count_persons, get_person_by_id from app.services.customer_quick_entry_service import resolve_or_create_quick_customer @@ -23,6 +24,32 @@ def _require_business_access(ctx: AuthContext, business_id: int) -> None: ) +def _require_quick_sales_permission( + ctx: AuthContext, + db: Session, + business_id: int, + action: str, + *, + people_action: str | None = None, +) -> None: + _require_business_access(ctx, business_id) + quick_sales_allowed = has_business_permission_for_business( + ctx, db, int(business_id), "quick_sales", action + ) + people_allowed = bool( + people_action + and has_business_permission_for_business( + ctx, db, int(business_id), "people", people_action + ) + ) + if not quick_sales_allowed and not people_allowed: + raise ApiError( + "FORBIDDEN", + f"Missing business permission: quick_sales.{action}", + http_status=403, + ) + + class CustomerSearchRequest(BaseModel): business_id: int page: int = 1 @@ -93,7 +120,13 @@ async def quick_resolve_customer( ctx: AuthContext = Depends(get_current_user), db: Session = Depends(get_db), ): - _require_business_access(ctx, payload.business_id) + _require_quick_sales_permission( + ctx, + db, + payload.business_id, + "create_customer", + people_action="add", + ) resolution = resolve_or_create_quick_customer( db, business_id=payload.business_id, @@ -151,7 +184,13 @@ async def search_customers( db: Session = Depends(get_db), ): """جست‌وجو در لیست مشتری‌ها""" - _require_business_access(ctx, search_request.business_id) + _require_quick_sales_permission( + ctx, + db, + search_request.business_id, + "view_customer_contact", + people_action="view", + ) # جست‌وجو در اشخاص persons = search_persons( diff --git a/hesabixAPI/adapters/api/v1/invoices.py b/hesabixAPI/adapters/api/v1/invoices.py index 469efa83..d68a8b0c 100755 --- a/hesabixAPI/adapters/api/v1/invoices.py +++ b/hesabixAPI/adapters/api/v1/invoices.py @@ -29,6 +29,7 @@ from app.core.permissions import ( ) from app.core.responses import success_response, format_datetime_fields from app.core.cache import get_cache +from app.core.transaction_lock import acquire_transaction_lock from adapters.api.v1.schemas import QueryInfo, InvoiceListQuery from adapters.api.v1.list_query_common import model_to_legacy_body from adapters.db.models.document import Document @@ -222,6 +223,36 @@ def create_invoice_endpoint( # پس از کنترل ویژگی فروش سریع، تنظیمات کسب‌وکار و مجوز کاربر در سرور ساخته می‌شود. extra = dict(payload.get("extra_info") or {}) extra.pop("_stock_override", None) + if extra.get("quick_sale") is True: + if payload.get("invoice_type") != "invoice_sales": + raise ApiError( + "QUICK_SALE_INVOICE_TYPE_INVALID", + "فروش سریع فقط برای فاکتور فروش قابل استفاده است", + http_status=400, + ) + request_id = str(extra.get("quick_sale_request_id") or "").strip() + if not re.fullmatch(r"[A-Za-z0-9._:-]{16,160}", request_id): + raise ApiError( + "QUICK_SALE_REQUEST_ID_REQUIRED", + "شناسه یکتای درخواست فروش سریع نامعتبر است", + http_status=400, + ) + acquire_transaction_lock( + db, + f"quick_sale_invoice:{business_id}:{request_id}", + ) + existing_invoice = db.query(Document).filter( + Document.business_id == int(business_id), + Document.document_type == "invoice_sales", + Document.extra_info["quick_sale"].as_string() == "true", + Document.extra_info["quick_sale_request_id"].as_string() == request_id, + ).first() + if existing_invoice is not None: + return success_response( + data=invoice_document_to_dict(db, existing_invoice), + request=request, + message="INVOICE_ALREADY_CREATED", + ) requested_override = payload.pop("stock_override", None) if requested_override is not None: from adapters.db.models.quick_sales_settings import QuickSalesSetting diff --git a/hesabixAPI/adapters/api/v1/quick_sales.py b/hesabixAPI/adapters/api/v1/quick_sales.py index a9c8fde6..dac0df42 100755 --- a/hesabixAPI/adapters/api/v1/quick_sales.py +++ b/hesabixAPI/adapters/api/v1/quick_sales.py @@ -20,6 +20,7 @@ from app.core.responses import ApiError, success_response from app.services.quick_sales_service import ( create_quick_sales_payment_button, delete_quick_sales_payment_button, + get_configured_anonymous_customer, get_or_create_anonymous_customer, get_quick_sales_customer_balance, get_quick_sales_settings, @@ -39,6 +40,25 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix="/businesses/{business_id}/quick-sales", tags=["quick-sales"]) +def _anonymous_customer_data(customer) -> dict: + person_types = [] + if customer.person_types: + try: + parsed_types = json.loads(customer.person_types) + person_types = parsed_types if isinstance(parsed_types, list) else [] + except (json.JSONDecodeError, TypeError) as exc: + logger.warning( + "Failed to parse person_types for customer %s: %s", + customer.id, + exc, + ) + return { + "id": customer.id, + "name": customer.alias_name, + "is_customer": PersonType.CUSTOMER.value in person_types, + } + + def _can(ctx: AuthContext, db: Session, business_id: int, section: str, action: str) -> bool: return has_business_permission_for_business(ctx, db, business_id, section, action) @@ -57,7 +77,9 @@ def get_customer_balance_endpoint( person_id: int, currency_id: int, as_of_date: date, - _: None = Depends(require_business_access_dep), + _: None = Depends( + require_business_permission_dep("quick_sales", "view_customer_balance") + ), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: @@ -107,6 +129,21 @@ def update_quick_sales_settings_endpoint( @router.get( + "/anonymous-customer", + summary="دریافت مشتری ناشناس تنظیم‌شده", +) +def read_anonymous_customer_endpoint( + request: Request, + business_id: int, + _: None = Depends(require_business_permission_dep("invoices", "add")), + db: Session = Depends(get_db), + ctx: AuthContext = Depends(get_current_user), +) -> dict: + customer = get_configured_anonymous_customer(db, business_id) + return success_response(_anonymous_customer_data(customer), request) + + +@router.post( "/anonymous-customer", summary="دریافت یا ایجاد مشتری ناشناس", description="دریافت مشتری ناشناس پیش‌فرض یا ایجاد آن در صورت عدم وجود", @@ -114,28 +151,14 @@ def update_quick_sales_settings_endpoint( def get_anonymous_customer_endpoint( request: Request, business_id: int, - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: """دریافت یا ایجاد مشتری ناشناس""" try: customer = get_or_create_anonymous_customer(db, business_id) - # بررسی اینکه آیا مشتری است یا نه - person_types = [] - if customer.person_types: - try: - parsed_types = json.loads(customer.person_types) - person_types = parsed_types if isinstance(parsed_types, list) else [] - except (json.JSONDecodeError, TypeError) as e: - logger.warning(f"Failed to parse person_types for customer {customer.id}: {e}") - person_types = [] - is_customer = PersonType.CUSTOMER.value in person_types - return success_response({ - "id": customer.id, - "name": customer.alias_name, - "is_customer": is_customer, - }, request) + return success_response(_anonymous_customer_data(customer), request) except Exception as e: logger.error(f"Error in get_anonymous_customer_endpoint for business {business_id}: {type(e).__name__}: {str(e)}", exc_info=True) raise @@ -145,7 +168,7 @@ def get_anonymous_customer_endpoint( def list_payment_buttons_endpoint( request: Request, business_id: int, - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: @@ -158,7 +181,7 @@ def create_payment_button_endpoint( request: Request, business_id: int, payload: Dict[str, Any] = Body(...), - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: @@ -177,7 +200,7 @@ def reorder_payment_buttons_endpoint( request: Request, business_id: int, payload: Dict[str, Any] = Body(...), - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: @@ -200,7 +223,7 @@ def update_payment_button_shortcut_endpoint( business_id: int, button_key: str, payload: Dict[str, Any] = Body(...), - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: @@ -276,7 +299,7 @@ def update_payment_button_endpoint( business_id: int, button_id: int, payload: Dict[str, Any] = Body(...), - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: @@ -296,7 +319,7 @@ def delete_payment_button_endpoint( request: Request, business_id: int, button_id: int, - _: None = Depends(require_business_access_dep), + _: None = Depends(require_business_permission_dep("invoices", "add")), db: Session = Depends(get_db), ctx: AuthContext = Depends(get_current_user), ) -> dict: diff --git a/hesabixAPI/app/services/customer_quick_entry_service.py b/hesabixAPI/app/services/customer_quick_entry_service.py index a8103efe..96ea7c78 100644 --- a/hesabixAPI/app/services/customer_quick_entry_service.py +++ b/hesabixAPI/app/services/customer_quick_entry_service.py @@ -251,6 +251,48 @@ def load_quick_customer_candidates( return query.limit(int(limit)).all() +def load_exact_quick_customer_candidates( + db: Session, + *, + business_id: int, + alias_name: str | None, +) -> list[Person]: + """تطبیق دقیق نام را مستقل از سقف نتایج مشابه انجام می‌دهد.""" + if not alias_name: + return [] + variants = alias_search_variants(alias_name) + name_columns = ( + Person.alias_name, + Person.first_name, + Person.last_name, + Person.company_name, + ) + exact_filters = [ + func.lower(func.trim(column)) == variant.casefold() + for column in name_columns + for variant in variants + ] + full_name = func.trim( + func.concat( + func.coalesce(Person.first_name, ""), + " ", + func.coalesce(Person.last_name, ""), + ) + ) + exact_filters.extend( + func.lower(full_name) == variant.casefold() for variant in variants + ) + return ( + db.query(Person) + .filter( + Person.business_id == int(business_id), + or_(*exact_filters), + ) + .order_by(Person.id) + .all() + ) + + def resolve_or_create_quick_customer( db: Session, *, @@ -276,12 +318,26 @@ def resolve_or_create_quick_customer( {"namespace": 1129665364, "business_id": int(business_id)}, ) + exact_persons = ( + load_exact_quick_customer_candidates( + db, + business_id=int(business_id), + alias_name=cleaned_alias, + ) + if not normalized_mobile + else [] + ) persons = load_quick_customer_candidates( db, business_id=int(business_id), alias_name=cleaned_alias, mobile=normalized_mobile, ) + if exact_persons: + seen_ids = {int(person.id) for person in exact_persons} + persons = exact_persons + [ + person for person in persons if int(person.id) not in seen_ids + ] matches = find_quick_customer_matches( persons, alias_name=cleaned_alias, diff --git a/hesabixAPI/app/services/inventory_discrepancy_service.py b/hesabixAPI/app/services/inventory_discrepancy_service.py index 9dfe9c65..a828c05f 100644 --- a/hesabixAPI/app/services/inventory_discrepancy_service.py +++ b/hesabixAPI/app/services/inventory_discrepancy_service.py @@ -214,8 +214,9 @@ def list_cases(db: Session, business_id: int, status: str | None = None) -> dict ).filter(InventoryDiscrepancyCase.business_id == int(business_id)) if status: q = q.filter(InventoryDiscrepancyCase.status == str(status)) + total = q.order_by(None).count() rows = q.order_by(InventoryDiscrepancyCase.created_at.desc()).limit(200).all() - return {"items": [_serialize(row) for row in rows], "total": len(rows)} + return {"items": [_serialize(row) for row in rows], "total": total} def get_case(db: Session, business_id: int, case_id: int) -> InventoryDiscrepancyCase: @@ -324,6 +325,10 @@ def resolve_case_with_goods_income( user_can_post: bool, user_can_change_unit_cost: bool, ) -> dict[str, Any]: + acquire_transaction_lock( + db, + f"inventory_discrepancy_resolution:{business_id}:{case_id}", + ) case = get_case(db, business_id, case_id) if case.status != "open": raise ApiError("INVENTORY_DISCREPANCY_ALREADY_RESOLVED", "این پرونده قبلاً رسیدگی شده است", http_status=409) diff --git a/hesabixAPI/app/services/invoice_service.py b/hesabixAPI/app/services/invoice_service.py index cd7b6d98..611e70e3 100755 --- a/hesabixAPI/app/services/invoice_service.py +++ b/hesabixAPI/app/services/invoice_service.py @@ -32,6 +32,7 @@ from adapters.db.models.product_bom import ProductBOM, ProductBOMOutput from adapters.db.models.business import Business from app.core.calendar import CalendarConverter, CalendarType from app.core.responses import ApiError, success_response +from app.core.transaction_lock import acquire_transaction_lock from app.services.document_monetization_service import ensure_document_policy_allows_creation from app.services.credit_service import get_business_credit_settings import jdatetime @@ -1577,6 +1578,24 @@ def _validate_outgoing_stock_before_invoice_commit( ) if not lines_to_check: return + # کنترل و ثبت خروج انبار در یک تراکنش انجام می‌شوند. قفل‌های مرتب‌شده + # مانع عبور هم‌زمان دو فروش از روی یک موجودی می‌شوند. + stock_lock_keys = sorted( + { + ( + int(line.get("product_id")), + int((line.get("extra_info") or {}).get("warehouse_id")), + ) + for line in lines_to_check + if line.get("product_id") is not None + and (line.get("extra_info") or {}).get("warehouse_id") is not None + } + ) + for product_id, warehouse_id in stock_lock_keys: + acquire_transaction_lock( + db, + f"inventory_stock:{business_id}:{warehouse_id}:{product_id}", + ) shortages = collect_stock_shortages( db, business_id, document.document_date, lines_to_check, # InvoiceItemLineهای سند جاری پیش از این کنترل flush شده‌اند. اگر خود سند @@ -1869,6 +1888,76 @@ def _extract_totals_from_lines(lines: List[Dict[str, Any]]) -> Dict[str, Decimal } +def _canonicalize_quick_sale_line_amounts(lines: List[Dict[str, Any]]) -> None: + """Rebuild monetary line fields used by quick sales from their inputs.""" + for line in lines: + info = dict(line.get("extra_info") or {}) + try: + qty = Decimal(str(line.get("quantity", 0) or 0)) + unit_price = Decimal( + str(info.get("unit_price", line.get("unit_price", 0)) or 0) + ) + discount_type = str( + info.get("discount_type", line.get("discount_type", "percent")) + or "percent" + ).strip().lower() + discount_value = Decimal( + str(info.get("discount_value", line.get("discount_value", 0)) or 0) + ) + tax_rate = Decimal( + str(info.get("tax_rate", line.get("tax_rate", 0)) or 0) + ) + except Exception as exc: + raise ApiError( + "INVALID_QUICK_SALE_LINE_AMOUNT", + "مقادیر مالی یکی از ردیف‌های فروش سریع نامعتبر است", + http_status=400, + ) from exc + if qty <= 0 or unit_price < 0 or discount_value < 0 or tax_rate < 0: + raise ApiError( + "INVALID_QUICK_SALE_LINE_AMOUNT", + "تعداد، قیمت، تخفیف یا مالیات ردیف نامعتبر است", + http_status=400, + ) + gross = qty * unit_price + if discount_type == "percent": + if discount_value > 100: + raise ApiError( + "INVALID_QUICK_SALE_LINE_DISCOUNT", + "درصد تخفیف ردیف باید بین صفر تا صد باشد", + http_status=400, + ) + line_discount = gross * discount_value / Decimal(100) + elif discount_type == "amount": + line_discount = discount_value + else: + raise ApiError( + "INVALID_QUICK_SALE_LINE_DISCOUNT", + "نوع تخفیف ردیف نامعتبر است", + http_status=400, + ) + if line_discount > gross: + raise ApiError( + "INVALID_QUICK_SALE_LINE_DISCOUNT", + "تخفیف ردیف نمی‌تواند از مبلغ ردیف بیشتر باشد", + http_status=400, + ) + taxable = gross - line_discount + tax_amount = taxable * tax_rate / Decimal(100) + info.update( + { + "unit_price": float(unit_price), + "discount_type": discount_type, + "discount_value": float(discount_value), + "line_discount": float(line_discount), + "tax_rate": float(tax_rate), + "tax_amount": float(tax_amount), + "line_total": float(taxable + tax_amount), + } + ) + line["extra_info"] = info + + def _extract_cogs_total(lines: List[Dict[str, Any]]) -> Decimal: total = Decimal(0) for line in lines: @@ -2851,6 +2940,15 @@ def _normalize_quick_sale_customer_balance_application( from app.services.quick_sales_service import get_quick_sales_customer_balance + # مانده یک شخص/ارز باید تا پایان ثبت فاکتور ثابت بماند تا دو صندوق + # نتوانند یک اعتبار قبلی را هم‌زمان در دو فروش مصرف کنند. + acquire_transaction_lock( + db, + ( + "quick_sales_customer_balance:" + f"{business_id}:{fiscal_year_id}:{person_id}:{currency_id}" + ), + ) current = get_quick_sales_customer_balance( db, business_id=business_id, @@ -3215,14 +3313,21 @@ def _create_quick_sale_change_payment( "invoice_id": int(document.id), "person_is_receivable": True, "gross_received": float( - change_amount - + Decimal( - str( - ((document.extra_info or {}).get("totals") or {}).get( - "net", 0 + sum( + ( + max( + Decimal(0), + Decimal( + str( + item.get("settles_amount") + if item.get("settles_amount") is not None + else item.get("amount", 0) + ) + ), ) - or 0 - ) + for item in payments + ), + Decimal(0), ) ), "overpayment_amount": float(change_amount), @@ -5271,10 +5376,13 @@ def create_invoice( except Exception: pass data["extra_info"] = header_extra + if header_extra.get("quick_sale") is True: + _canonicalize_quick_sale_line_amounts(lines_input) + global_discount_applied = False try: from app.services.invoice_global_discount_service import apply_global_discount_to_invoice_payload - apply_global_discount_to_invoice_payload( + global_discount_applied = apply_global_discount_to_invoice_payload( db, business_id, invoice_type, lines_input, data ) except ApiError: @@ -5287,9 +5395,12 @@ def create_invoice( http_status=400, ) header_extra = dict(data.get("extra_info") or {}) - totals = (header_extra.get("totals") or {}) if isinstance(header_extra, dict) else {} - totals_missing = not all(k in totals for k in ("gross", "discount", "tax", "net")) - if totals_missing: + # جمع کلاینت مرجع ثبت حسابداری نیست. سرویس تخفیف کلی، در صورت وجود، + # totals را از ردیف‌ها ساخته است؛ در سایر حالت‌ها نیز مستقیماً از ردیف‌ها + # محاسبه می‌کنیم. + if global_discount_applied: + totals = dict(header_extra.get("totals") or {}) + else: totals = _extract_totals_from_lines(lines_input) header_extra["totals"] = totals data["extra_info"] = header_extra diff --git a/hesabixAPI/app/services/quick_sales_service.py b/hesabixAPI/app/services/quick_sales_service.py index 22416baa..97593754 100755 --- a/hesabixAPI/app/services/quick_sales_service.py +++ b/hesabixAPI/app/services/quick_sales_service.py @@ -9,7 +9,6 @@ from typing import Any, Dict, List from sqlalchemy import and_, func, or_ from sqlalchemy.orm import Session -from adapters.api.v1.schema_models.person import PersonCreateRequest from adapters.db.models.bank_account import BankAccount from adapters.db.models.business import Business from adapters.db.models.cash_register import CashRegister @@ -19,8 +18,12 @@ from adapters.db.models.person import Person, PersonType from adapters.db.models.quick_sales_payment_button import QuickSalesPaymentButton from adapters.db.models.quick_sales_settings import QuickSalesSetting from app.core.responses import ApiError +from app.core.transaction_lock import acquire_transaction_lock from app.services.person_group_service import assert_assignable_person_group -from app.services.person_service import calculate_person_balances_by_currency, create_person +from app.services.person_service import ( + calculate_person_balances_by_currency, + invalidate_persons_cache, +) from app.services.user_ui_preferences_service import ( get_quick_sales_payment_shortcuts, save_quick_sales_payment_shortcuts, @@ -248,7 +251,7 @@ def _payment_button_target_id(row: QuickSalesPaymentButton) -> int: def _payment_button_to_dict(db: Session, row: QuickSalesPaymentButton) -> Dict[str, Any]: - _, target_name = _payment_button_target( + target, target_name = _payment_button_target( db, row.business_id, row.target_type, _payment_button_target_id(row) ) # برای شخص، خود نام شخص روی دکمه نمایش داده می‌شود تا عنوان مبهمی مثل «کارت شخصی» نسازیم. @@ -261,6 +264,11 @@ def _payment_button_to_dict(db: Session, row: QuickSalesPaymentButton) -> Dict[s "target_type": row.target_type, "target_id": _payment_button_target_id(row), "target_name": target_name, + "target_currency_id": ( + int(target.currency_id) + if row.target_type in {"cash_register", "bank"} + else None + ), "label": label, # Shared-button defaults are stored by platform on the button row. # Personal choices live in user_ui_preferences and are resolved below. @@ -505,7 +513,7 @@ def list_quick_sales_payment_buttons( if not register_id: return [] try: - _, name = _payment_button_target(db, business_id, "cash_register", register_id) + target, name = _payment_button_target(db, business_id, "cash_register", register_id) except ApiError: return [] return _apply_user_payment_shortcuts(db, business_id=business_id, user_id=user_id, buttons=[{ @@ -516,6 +524,7 @@ def list_quick_sales_payment_buttons( "target_type": "cash_register", "target_id": int(register_id), "target_name": name, + "target_currency_id": int(target.currency_id), "label": name, "default_shortcuts": {"windows": None, "web": None}, "position": 0, @@ -1284,10 +1293,16 @@ def update_quick_sales_settings(db: Session, business_id: int, payload: Dict[str if "default_currency_id" in payload: currency_id = payload.get("default_currency_id") if currency_id is not None: - from adapters.db.models.currency import Currency - currency = db.query(Currency).filter(Currency.id == int(currency_id)).first() - if not currency: - raise ApiError("CURRENCY_NOT_FOUND", "ارز یافت نشد", http_status=404) + business_currency = db.query(BusinessCurrency).filter( + BusinessCurrency.business_id == int(business_id), + BusinessCurrency.currency_id == int(currency_id), + ).first() + if not business_currency: + raise ApiError( + "BUSINESS_CURRENCY_NOT_FOUND", + "این ارز برای کسب‌وکار فعال نیست", + http_status=400, + ) obj.default_currency_id = int(currency_id) if currency_id is not None else None if "default_price_list_id" in payload: @@ -1309,6 +1324,21 @@ def update_quick_sales_settings(db: Session, business_id: int, payload: Dict[str if "print_template_id" in payload: template_id = payload.get("print_template_id") + if template_id is not None: + from adapters.db.models.report_template import ReportTemplate + + template = db.query(ReportTemplate).filter( + ReportTemplate.id == int(template_id), + ReportTemplate.business_id == int(business_id), + ReportTemplate.module_key == "invoices", + ReportTemplate.status == "published", + ).first() + if template is None: + raise ApiError( + "PRINT_TEMPLATE_NOT_FOUND", + "قالب چاپ منتشرشده متعلق به این کسب‌وکار نیست", + http_status=400, + ) obj.print_template_id = int(template_id) if template_id is not None else None if "print_paper_size" in payload: @@ -1372,11 +1402,22 @@ def get_or_create_anonymous_customer( settings: Dict[str, Any] | None = None ) -> Person: """دریافت یا ایجاد مشتری ناشناس""" + acquire_transaction_lock(db, f"quick_sales_anonymous_customer:{business_id}") + settings_row = ( + db.query(QuickSalesSetting) + .filter(QuickSalesSetting.business_id == int(business_id)) + .first() + ) if settings is None: settings = get_quick_sales_settings(db, business_id) - - # بررسی مشتری پیش‌فرض - customer_id = settings.get("default_anonymous_customer_id") + + # شناسه ذخیره‌شده تنها مرجع تشخیص مشتری سیستمی است. نام نمایشی نباید + # باعث شود یک مشتری واقعی به اشتباه مشتری ناشناس شناخته شود. + customer_id = ( + settings_row.default_anonymous_customer_id + if settings_row is not None + else settings.get("default_anonymous_customer_id") + ) if customer_id: customer = db.query(Person).filter( and_( @@ -1387,95 +1428,33 @@ def get_or_create_anonymous_customer( ).first() if customer: return customer - - # جستجوی مشتری ناشناس موجود + customer_name = settings.get("anonymous_customer_name", "مشتری ناشناس") name_fa = str(customer_name) if customer_name else "مشتری ناشناس" - - # جستجوی مشتری با نام و نوع مشتری - # اولویت با مشتری‌هایی که کد دارند (کد None نباشد) - customer = db.query(Person).filter( - and_( - Person.business_id == int(business_id), - Person.alias_name == name_fa, - Person.person_types.like(f'%{PersonType.CUSTOMER.value}%'), - Person.code.isnot(None), # اولویت با مشتری‌هایی که کد دارند - ) - ).first() - - # اگر مشتری با کد پیدا نشد، مشتری بدون کد را جستجو کن - if not customer: - customer = db.query(Person).filter( - and_( - Person.business_id == int(business_id), - Person.alias_name == name_fa, - Person.person_types.like(f'%{PersonType.CUSTOMER.value}%'), - ) - ).first() - - if customer: - # به‌روزرسانی تنظیمات (مستقیماً بدون بررسی مجدد) - obj = ( - db.query(QuickSalesSetting) - .filter(QuickSalesSetting.business_id == int(business_id)) - .first() - ) - if not obj: - obj = QuickSalesSetting(business_id=int(business_id)) - db.add(obj) - obj.default_anonymous_customer_id = customer.id - db.flush() - db.commit() - return customer - - # ایجاد جدید با استفاده از create_person برای تولید صحیح کد + if settings.get("auto_create_anonymous_customer", True): - # استفاده از create_person برای تولید صحیح کد - person_data = PersonCreateRequest( + next_code = ( + db.query(func.max(Person.code)) + .filter(Person.business_id == int(business_id)) + .scalar() + or 0 + ) + 1 + customer = Person( + business_id=int(business_id), + code=next_code, alias_name=name_fa, - person_types=[PersonType.CUSTOMER], - code=None, # None = تولید خودکار کد + person_types=json.dumps([PersonType.CUSTOMER.value], ensure_ascii=False), ) - - result = create_person(db, int(business_id), person_data) - logger.debug(f"create_person result: {result}") - customer_id = result.get("data", {}).get("id") - - if not customer_id: - logger.error(f"Failed to get customer_id from create_person result: {result}") - raise ApiError( - "FAILED_TO_CREATE_ANONYMOUS_CUSTOMER", - "خطا در ایجاد مشتری ناشناس", - http_status=500 - ) - - # دریافت مشتری ایجاد شده - customer = db.query(Person).filter( - and_( - Person.id == int(customer_id), - Person.business_id == int(business_id), - ) - ).first() - - if not customer: - raise ApiError( - "ANONYMOUS_CUSTOMER_NOT_FOUND", - "مشتری ناشناس ایجاد شد اما یافت نشد", - http_status=500 - ) - - # به‌روزرسانی تنظیمات (مستقیماً بدون بررسی مجدد) - obj = ( - db.query(QuickSalesSetting) - .filter(QuickSalesSetting.business_id == int(business_id)) - .first() - ) - if not obj: - obj = QuickSalesSetting(business_id=int(business_id)) - db.add(obj) - obj.default_anonymous_customer_id = customer.id + db.add(customer) + db.flush() + if settings_row is None: + settings_row = QuickSalesSetting(business_id=int(business_id)) + db.add(settings_row) + settings_row.default_anonymous_customer_id = customer.id db.flush() db.commit() + db.refresh(customer) + invalidate_persons_cache(int(business_id), fiscal_year_id=None) return customer raise ApiError( @@ -1483,3 +1462,26 @@ def get_or_create_anonymous_customer( "مشتری ناشناس تعریف نشده است. لطفاً در تنظیمات فروش سریع یک مشتری پیش‌فرض انتخاب کنید.", http_status=400 ) + + +def get_configured_anonymous_customer(db: Session, business_id: int) -> Person: + """Return the explicitly configured anonymous customer without mutation.""" + row = ( + db.query(QuickSalesSetting) + .filter(QuickSalesSetting.business_id == int(business_id)) + .first() + ) + customer_id = row.default_anonymous_customer_id if row is not None else None + if customer_id is not None: + customer = db.query(Person).filter( + Person.id == int(customer_id), + Person.business_id == int(business_id), + Person.person_types.like(f'%{PersonType.CUSTOMER.value}%'), + ).first() + if customer is not None: + return customer + raise ApiError( + "ANONYMOUS_CUSTOMER_NOT_SET", + "مشتری ناشناس تعریف نشده است", + http_status=404, + ) diff --git a/hesabixAPI/migrations/versions/20261017_000001_quick_sales_audit_permissions.py b/hesabixAPI/migrations/versions/20261017_000001_quick_sales_audit_permissions.py new file mode 100644 index 00000000..6891d42f --- /dev/null +++ b/hesabixAPI/migrations/versions/20261017_000001_quick_sales_audit_permissions.py @@ -0,0 +1,68 @@ +"""Harden quick-sales permissions and invoice idempotency. + +Revision ID: 20261017_000001_quick_sales_audit_permissions +Revises: 20261015_000001_quick_sales_web_shortcut +""" + +from alembic import op + +revision = "20261017_000001_quick_sales_audit_permissions" +down_revision = "20261015_000001_quick_sales_web_shortcut" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute(""" + CREATE UNIQUE INDEX uq_documents_quick_sale_request + ON documents ( + business_id, + (extra_info ->> 'quick_sale_request_id') + ) + WHERE document_type = 'invoice_sales' + AND extra_info ->> 'quick_sale' = 'true' + AND extra_info ->> 'quick_sale_request_id' IS NOT NULL + """) + # کاربران فعلی دارای مجوز ثبت فاکتور، رفتار جاری فروش سریع را از دست + # نمی‌دهند؛ از این پس مالک می‌تواند هر مجوز را جداگانه ویرایش کند. + op.execute(""" + UPDATE business_permissions + SET business_permissions = jsonb_set( + COALESCE(business_permissions::jsonb, '{}'::jsonb), + '{quick_sales}', + jsonb_build_object( + 'create_customer', true, + 'view_customer_contact', true, + 'view_customer_balance', true + ) || COALESCE( + business_permissions::jsonb -> 'quick_sales', + '{}'::jsonb + ), + true + )::json + WHERE COALESCE( + (business_permissions::jsonb -> 'invoices' ->> 'add')::boolean, + false + ) = true + OR COALESCE( + (business_permissions::jsonb -> 'invoices' ->> 'write')::boolean, + false + ) = true + OR COALESCE( + (business_permissions::jsonb -> 'invoices' ->> 'edit')::boolean, + false + ) = true + """) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS uq_documents_quick_sale_request") + op.execute(""" + UPDATE business_permissions + SET business_permissions = ( + business_permissions::jsonb + #- '{quick_sales,create_customer}' + #- '{quick_sales,view_customer_contact}' + #- '{quick_sales,view_customer_balance}' + )::json + """) diff --git a/hesabixAPI/tests/test_customer_quick_entry_service.py b/hesabixAPI/tests/test_customer_quick_entry_service.py index 2d2b456a..ab70cd09 100644 --- a/hesabixAPI/tests/test_customer_quick_entry_service.py +++ b/hesabixAPI/tests/test_customer_quick_entry_service.py @@ -271,7 +271,7 @@ async def test_quick_resolve_requires_business_access(monkeypatch): @pytest.mark.asyncio -async def test_quick_resolve_allows_business_member(monkeypatch): +async def test_quick_resolve_allows_authorized_quick_sales_user(monkeypatch): from adapters.api.v1 import customers as customers_api from adapters.api.v1.customers import ( CustomerQuickResolveRequest, @@ -283,6 +283,11 @@ async def test_quick_resolve_allows_business_member(monkeypatch): user.id = 1 ctx = AuthContext(user=user, api_key_id=1, db=Mock()) ctx.can_access_business = Mock(return_value=True) + monkeypatch.setattr( + customers_api, + "has_business_permission_for_business", + lambda *_args, **_kwargs: True, + ) person = _person(7, "علی رضایی", mobile="09121234567") monkeypatch.setattr( @@ -309,3 +314,37 @@ async def test_quick_resolve_allows_business_member(monkeypatch): assert len(response.customers) == 1 assert response.customers[0].id == 7 ctx.can_access_business.assert_called_once_with(15) + + +@pytest.mark.asyncio +async def test_quick_resolve_rejects_member_without_customer_permission( + monkeypatch, +): + from adapters.api.v1 import customers as customers_api + from adapters.api.v1.customers import ( + CustomerQuickResolveRequest, + quick_resolve_customer, + ) + + user = Mock() + user.id = 1 + ctx = AuthContext(user=user, api_key_id=1, db=Mock()) + ctx.can_access_business = Mock(return_value=True) + monkeypatch.setattr( + customers_api, + "has_business_permission_for_business", + lambda *_args, **_kwargs: False, + ) + + with pytest.raises(ApiError) as exc: + await quick_resolve_customer( + request=Mock(), + payload=CustomerQuickResolveRequest( + business_id=15, + alias_name="علی رضایی", + ), + ctx=ctx, + db=Mock(), + ) + + assert exc.value.status_code == 403 diff --git a/hesabixAPI/tests/test_quick_sales_audit_hardening.py b/hesabixAPI/tests/test_quick_sales_audit_hardening.py new file mode 100644 index 00000000..4cc6a651 --- /dev/null +++ b/hesabixAPI/tests/test_quick_sales_audit_hardening.py @@ -0,0 +1,96 @@ +from unittest.mock import MagicMock +import inspect + +import pytest + +from app.core.responses import ApiError +from app.services.invoice_service import ( + _canonicalize_quick_sale_line_amounts, + _extract_totals_from_lines, +) + + +def test_quick_sale_line_money_is_rebuilt_from_canonical_inputs() -> None: + lines = [ + { + "product_id": 7, + "quantity": 2, + "extra_info": { + "unit_price": 100, + "discount_type": "percent", + "discount_value": 10, + "tax_rate": 10, + # مقادیر جعلی که نباید وارد سند شوند. + "line_discount": 199, + "tax_amount": 9000, + "line_total": 1, + }, + } + ] + + _canonicalize_quick_sale_line_amounts(lines) + totals = _extract_totals_from_lines(lines) + + assert lines[0]["extra_info"]["line_discount"] == 20 + assert lines[0]["extra_info"]["tax_amount"] == 18 + assert lines[0]["extra_info"]["line_total"] == 198 + assert float(totals["net"]) == 198 + + +def test_quick_sale_line_rejects_discount_above_line_gross() -> None: + lines = [ + { + "product_id": 7, + "quantity": 1, + "extra_info": { + "unit_price": 100, + "discount_type": "amount", + "discount_value": 101, + "tax_rate": 0, + }, + } + ] + + with pytest.raises(ApiError) as exc_info: + _canonicalize_quick_sale_line_amounts(lines) + + assert exc_info.value.code == "INVALID_QUICK_SALE_LINE_DISCOUNT" + + +def test_quick_sale_invoice_requires_stable_request_id() -> None: + from adapters.api.v1.invoices import create_invoice_endpoint + + with pytest.raises(ApiError) as exc_info: + inspect.unwrap(create_invoice_endpoint)( + request=MagicMock(), + business_id=5, + payload={ + "invoice_type": "invoice_sales", + "extra_info": {"quick_sale": True}, + }, + ctx=MagicMock(), + db=MagicMock(), + ) + + assert exc_info.value.code == "QUICK_SALE_REQUEST_ID_REQUIRED" + + +def test_quick_sale_rejects_non_sales_invoice_type() -> None: + from adapters.api.v1.invoices import create_invoice_endpoint + + with pytest.raises(ApiError) as exc_info: + inspect.unwrap(create_invoice_endpoint)( + request=MagicMock(), + business_id=5, + payload={ + "invoice_type": "invoice_purchase", + "extra_info": { + "quick_sale": True, + "quick_sale_request_id": "8ef087a7-cadc-4b69-9366-163b40723b37", + }, + }, + ctx=MagicMock(), + db=MagicMock(), + ) + + assert exc_info.value.code == "QUICK_SALE_INVOICE_TYPE_INVALID" diff --git a/hesabixUI/hesabix_ui/lib/models/quick_sales_parked_sale.dart b/hesabixUI/hesabix_ui/lib/models/quick_sales_parked_sale.dart index c0ed3fce..211e9faa 100644 --- a/hesabixUI/hesabix_ui/lib/models/quick_sales_parked_sale.dart +++ b/hesabixUI/hesabix_ui/lib/models/quick_sales_parked_sale.dart @@ -390,12 +390,22 @@ class QuickSalesParkedSalesBundle { class QuickSalesParkedSalesStorage { static const prefix = 'quick_sales_parked_sales_'; - static String keyFor(int businessId) => '$prefix$businessId'; + static String keyFor(int businessId, int userId, {String? scope}) { + final base = '$prefix${businessId}_user_$userId'; + final cleanScope = scope?.trim(); + return cleanScope == null || cleanScope.isEmpty + ? base + : '${base}_scope_$cleanScope'; + } - static Future load(int businessId) async { + static Future load( + int businessId, + int userId, { + String? scope, + }) async { try { final prefs = await SharedPreferences.getInstance(); - final raw = prefs.getString(keyFor(businessId)); + final raw = prefs.getString(keyFor(businessId, userId, scope: scope)); if (raw == null || raw.isEmpty) return null; return QuickSalesParkedSalesBundle.tryParse(jsonDecode(raw)); } catch (_) { @@ -403,14 +413,21 @@ class QuickSalesParkedSalesStorage { } } - static Future save( + static Future save( int businessId, - QuickSalesParkedSalesBundle bundle, - ) async { + int userId, + QuickSalesParkedSalesBundle bundle, { + String? scope, + }) async { try { final prefs = await SharedPreferences.getInstance(); - await prefs.setString(keyFor(businessId), jsonEncode(bundle.toJson())); - } catch (_) {} + return await prefs.setString( + keyFor(businessId, userId, scope: scope), + jsonEncode(bundle.toJson()), + ); + } catch (_) { + return false; + } } } diff --git a/hesabixUI/hesabix_ui/lib/models/quick_sales_payment_button.dart b/hesabixUI/hesabix_ui/lib/models/quick_sales_payment_button.dart index d9c1cfea..4f40412e 100644 --- a/hesabixUI/hesabix_ui/lib/models/quick_sales_payment_button.dart +++ b/hesabixUI/hesabix_ui/lib/models/quick_sales_payment_button.dart @@ -37,6 +37,7 @@ class QuickSalesPaymentButtonModel { final QuickSalesPaymentTargetType targetType; final int targetId; final String targetName; + final int? targetCurrencyId; final String label; final String? defaultShortcut; final String? userShortcut; @@ -56,6 +57,7 @@ class QuickSalesPaymentButtonModel { required this.targetType, required this.targetId, required this.targetName, + required this.targetCurrencyId, required this.label, required this.defaultShortcut, required this.userShortcut, @@ -108,6 +110,7 @@ class QuickSalesPaymentButtonModel { targetType: target, targetId: (json['target_id'] as num).toInt(), targetName: (json['target_name'] ?? '').toString(), + targetCurrencyId: (json['target_currency_id'] as num?)?.toInt(), label: (json['label'] ?? json['target_name'] ?? '').toString(), defaultShortcut: json['default_shortcut']?.toString(), userShortcut: json['user_shortcut']?.toString(), diff --git a/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_page.dart index 9dddbea6..9ba25df3 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_page.dart @@ -53,6 +53,7 @@ import '../../widgets/inputs/frequent_description_text_field.dart'; import '../../widgets/barcode/web_barcode_scan_screen.dart'; import '../../utils/general_barcode_utils.dart'; import '../../utils/responsive_helper.dart'; +import '../../utils/web/web_utils.dart'; import 'package:hesabix_ui/services/bytes_export/bytes_export_service.dart'; import 'package:hesabix_ui/theme/semantic_color_resolver.dart'; @@ -154,8 +155,15 @@ class _QuickSalesPageState extends State final CategoryService _categoryService = CategoryService(ApiClient()); bool _loading = true; + bool _parkedStorageWarningShown = false; + late final String? _parkedStorageScope = getOrCreateSessionStorageValue( + 'hesabix_quick_sales_tab_scope_v1', + QuickSalesParkedSale.newId(), + ); _QuickSalesSaveAction _saveAction = _QuickSalesSaveAction.none; bool get _isSaving => _saveAction != _QuickSalesSaveAction.none; + String _errorText(Object error) => + mounted ? ErrorExtractor.forContext(error, context) : error.toString(); Map? _settings; Customer? _anonymousCustomer; @@ -170,7 +178,7 @@ class _QuickSalesPageState extends State Timer? _stockBatchTimer; // کش قیمت لیست قیمت (per session) - final Map _priceListCache = {}; + final Map _priceListCache = {}; // جستجو / افزودن به سبد bool _barcodeSearching = false; @@ -328,7 +336,6 @@ class _QuickSalesPageState extends State _restoreDesktopRailAfterQuit = () => scope.setRailVisible(true); } _barcodeFocus.requestFocus(); - _keyboardListenerFocus.requestFocus(); }); } @@ -456,10 +463,12 @@ class _QuickSalesPageState extends State unawaited( QuickSalesParkedSalesStorage.save( widget.businessId, + widget.authStore.currentUserId ?? 0, QuickSalesParkedSalesBundle( activeId: _activeSaleId, sales: List.of(_sales), ), + scope: _parkedStorageScope, ), ); } @@ -645,13 +654,23 @@ class _QuickSalesPageState extends State Future _persistParkedSalesNow() async { if (!_parkedHydrated || _activeSaleId.isEmpty) return; _captureActiveSaleIntoList(); - await QuickSalesParkedSalesStorage.save( + final saved = await QuickSalesParkedSalesStorage.save( widget.businessId, + widget.authStore.currentUserId ?? 0, QuickSalesParkedSalesBundle( activeId: _activeSaleId, sales: List.of(_sales), ), + scope: _parkedStorageScope, ); + if (!saved && mounted && !_parkedStorageWarningShown) { + _parkedStorageWarningShown = true; + SnackBarHelper.show( + context, + message: 'ذخیره محلی فروش‌های پارک‌شده انجام نشد.', + isError: true, + ); + } } void _captureActiveSaleIntoList() { @@ -773,7 +792,11 @@ class _QuickSalesPageState extends State } Future _hydrateParkedSalesIntoFields() async { - final bundle = await QuickSalesParkedSalesStorage.load(widget.businessId); + final bundle = await QuickSalesParkedSalesStorage.load( + widget.businessId, + widget.authStore.currentUserId ?? 0, + scope: _parkedStorageScope, + ); if (!mounted) return; if (bundle == null || bundle.sales.isEmpty) { _activeSaleId = QuickSalesParkedSale.newId(); @@ -799,7 +822,6 @@ class _QuickSalesPageState extends State WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; _barcodeFocus.requestFocus(); - _keyboardListenerFocus.requestFocus(); }); if (_showInventory && _cartItems.isNotEmpty) { _refreshAllStocks(); @@ -1504,7 +1526,7 @@ class _QuickSalesPageState extends State } } } catch (e) { - notes.add(ErrorExtractor.forContext(e, context)); + notes.add(_errorText(e)); } } } @@ -1543,7 +1565,7 @@ class _QuickSalesPageState extends State } } } catch (e) { - notes.add(ErrorExtractor.forContext(e, context)); + notes.add(_errorText(e)); } } } @@ -1554,9 +1576,7 @@ class _QuickSalesPageState extends State return notes; } catch (e) { - notes.add( - '${t.quickSalesShareLinkFailed}: ${ErrorExtractor.forContext(e, context)}', - ); + notes.add('${t.quickSalesShareLinkFailed}: ${_errorText(e)}'); return notes; } } @@ -1867,6 +1887,7 @@ class _QuickSalesPageState extends State await _addToCart(product, skipHydrate: true); await _saveRecentProduct(product); + if (!mounted) return; // پاک کردن جستجوی ناموفق و فیلد جستجو setState(() { @@ -1877,8 +1898,7 @@ class _QuickSalesPageState extends State } catch (e) { SnackBarHelper.show( context, - message: - 'کالا ثبت شد اما خطا در افزودن به سبد: ${ErrorExtractor.forContext(e, context)}', + message: 'کالا ثبت شد اما خطا در افزودن به سبد: ${_errorText(e)}', isError: true, ); } @@ -1889,7 +1909,6 @@ class _QuickSalesPageState extends State }); _barcodeController.clear(); _barcodeFocus.requestFocus(); - SnackBarHelper.show(context, message: 'کالا با موفقیت ثبت شد'); } } else { // اگر دیالوگ بسته شد بدون ثبت، جستجوی ناموفق را نگه دار @@ -1917,13 +1936,13 @@ class _QuickSalesPageState extends State return num.tryParse(value.toString()) ?? defaultValue; } - Future _getPriceFromPriceList(int productId) async { + Future _getPriceFromPriceList(int productId) async { if (_priceListCache.containsKey(productId)) { - return _priceListCache[productId]!; + return _priceListCache[productId]; } // اگر لیست قیمت پیش‌فرض وجود ندارد یا ارز مشخص نشده، null برگردان if (_defaultPriceListId == null || _defaultCurrencyId == null) { - return 0; + return null; } try { @@ -1952,18 +1971,18 @@ class _QuickSalesPageState extends State } // اگر unit_id null باشد، یعنی قیمت برای واحد اصلی است - if (unitId == null && price != null && price > 0) { + if (unitId == null && price != null && price >= 0) { _priceListCache[productId] = price; return price; } } } catch (e) { - // در صورت خطا، 0 برگردان تا از قیمت پایه استفاده شود + // در صورت خطا، null برگردان تا از قیمت پایه استفاده شود debugPrint('خطا در دریافت قیمت از لیست قیمت: $e'); } - _priceListCache[productId] = 0; - return 0; + _priceListCache[productId] = null; + return null; } bool get _hasUniqueItemsInCart => @@ -2131,14 +2150,14 @@ class _QuickSalesPageState extends State if (_defaultPriceListId != null && _defaultCurrencyId != null) { final priceFromList = await _getPriceFromPriceList(productId); - if (priceFromList > 0) { + if (priceFromList != null) { unitPrice = priceFromList; unitPriceSource = 'priceList'; } } - // اگر قیمت از لیست قیمت پیدا نشد یا صفر بود، از قیمت پایه استفاده کن - if (unitPrice == 0) { + // صفر یک قیمت معتبر (هدیه/پروموشن) است؛ فقط نبود نتیجه fallback می‌شود. + if (unitPriceSource != 'priceList') { unitPrice = _toNum( product['base_sales_price'] ?? product['sales_price'], ); @@ -2664,9 +2683,16 @@ class _QuickSalesPageState extends State bool debtConfirmed = false, String? appliedStockCorrectionToken, }) async { + if (_isSaving) return; + setState(() { + _saveAction = print + ? _QuickSalesSaveAction.saveAndPrint + : _QuickSalesSaveAction.save; + }); // اعتبارسنجی سبد خرید if (_cartItems.isEmpty) { SnackBarHelper.show(context, message: 'سبد خرید خالی است', isError: true); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } @@ -2678,6 +2704,7 @@ class _QuickSalesPageState extends State 'ارز پیش‌فرض تنظیم نشده است. لطفاً در تنظیمات فاکتور سریع تنظیم کنید.', isError: true, ); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } @@ -2688,6 +2715,7 @@ class _QuickSalesPageState extends State message: 'برای صدور حواله انبار، انتخاب انبار الزامی است', isError: true, ); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } @@ -2697,6 +2725,7 @@ class _QuickSalesPageState extends State final paymentError = _validatePayments(t); if (paymentError != null) { SnackBarHelper.show(context, message: paymentError, isError: true); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } } @@ -2723,13 +2752,19 @@ class _QuickSalesPageState extends State ], ), ); - if (!mounted || confirmed != true) return; + if (!mounted || confirmed != true) { + if (mounted) setState(() => _saveAction = _QuickSalesSaveAction.none); + return; + } debtConfirmed = true; } QuickSalesChangeResolution? changeResolution = _validChangeResolution; if (_isOverpaid && changeResolution == null) { changeResolution = await _openChangeResolutionDialog(); - if (!mounted || changeResolution == null) return; + if (!mounted || changeResolution == null) { + if (mounted) setState(() => _saveAction = _QuickSalesSaveAction.none); + return; + } } if (_shouldShareAfterSave) { if (_shareOnlinePaymentEnabled) { @@ -2739,6 +2774,7 @@ class _QuickSalesPageState extends State message: t.quickSalesShareNoGateway, isError: true, ); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } if (_shareGatewayId == null) { @@ -2747,6 +2783,7 @@ class _QuickSalesPageState extends State message: t.quickSalesShareGatewayRequired, isError: true, ); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } } @@ -2760,6 +2797,7 @@ class _QuickSalesPageState extends State message: t.invoiceGlobalDiscountPercentInvalid, isError: true, ); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } if (_globalDiscountType == 'amount' && gv0 < 0) { @@ -2768,16 +2806,11 @@ class _QuickSalesPageState extends State message: t.invoiceGlobalDiscountAmountInvalid, isError: true, ); + setState(() => _saveAction = _QuickSalesSaveAction.none); return; } } - setState(() { - _saveAction = print - ? _QuickSalesSaveAction.saveAndPrint - : _QuickSalesSaveAction.save; - }); - final shouldPrint = print || _autoPrint; final shouldShare = _shouldShareAfterSave; final shareSnapshot = _QuickSalesShareSnapshot( @@ -2867,6 +2900,7 @@ class _QuickSalesPageState extends State // ساخت extra_info با person_id و تنظیمات حواله انبار final extraInfo = { 'quick_sale': true, + 'quick_sale_request_id': _activeSaleId, 'person_id': personId, // همیشه person_id را اضافه می‌کنیم 'post_inventory': _enableWarehouseDocument, // آیا حواله ایجاد شود؟ 'auto_post_warehouse': @@ -3042,9 +3076,7 @@ class _QuickSalesPageState extends State try { await _printInvoice(invoiceId: invoiceId, invoiceCode: invoiceCode); } catch (e) { - followUpNotes.add( - 'خطا در چاپ: ${ErrorExtractor.forContext(e, context)}', - ); + followUpNotes.add('خطا در چاپ: ${_errorText(e)}'); } } @@ -3059,7 +3091,7 @@ class _QuickSalesPageState extends State ); followUpNotes.addAll(shareNotes); } catch (e) { - followUpNotes.add(ErrorExtractor.forContext(e, context)); + followUpNotes.add(_errorText(e)); } } @@ -4677,6 +4709,7 @@ class _QuickSalesPageState extends State onConfigureChange: _openChangeResolutionDialog, defaultCashRegisterId: _selectedCashRegisterId, currencyUnit: _paymentCurrencyUnit, + currencyId: _defaultCurrencyId!, decimalPlaces: _invoiceCurrencyDecimalPlaces, enabled: !_isSaving, onSave: () => _saveInvoice(print: false), diff --git a/hesabixUI/hesabix_ui/lib/pages/business/users_permissions_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/users_permissions_page.dart index d1a0c471..d6d71ab8 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/users_permissions_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/users_permissions_page.dart @@ -1162,6 +1162,9 @@ class _PermissionsDialogState extends State<_PermissionsDialog> { 'change_unit_price': t.permissionInvoiceChangeUnitPrice, }, 'quick_sales': { + 'create_customer': 'ثبت سریع مشتری در فروش سریع', + 'view_customer_contact': 'مشاهده اطلاعات تماس مشتری در فروش سریع', + 'view_customer_balance': 'مشاهده مانده حساب مشتری در فروش سریع', 'manage_default_payment_shortcuts': 'مدیریت میانبرهای پیش‌فرض پرداخت در فروش سریع', }, diff --git a/hesabixUI/hesabix_ui/lib/services/quick_sales_service.dart b/hesabixUI/hesabix_ui/lib/services/quick_sales_service.dart index a086acb6..a2d43c4c 100755 --- a/hesabixUI/hesabix_ui/lib/services/quick_sales_service.dart +++ b/hesabixUI/hesabix_ui/lib/services/quick_sales_service.dart @@ -30,7 +30,7 @@ class QuickSalesService { Future> getAnonymousCustomer({ required int businessId, }) async { - final res = await _api.get>( + final res = await _api.post>( '/api/v1/businesses/$businessId/quick-sales/anonymous-customer', ); return Map.from(res.data?['data'] ?? const {}); diff --git a/hesabixUI/hesabix_ui/lib/utils/web/web_utils_stub.dart b/hesabixUI/hesabix_ui/lib/utils/web/web_utils_stub.dart index 86a1b870..3db58268 100755 --- a/hesabixUI/hesabix_ui/lib/utils/web/web_utils_stub.dart +++ b/hesabixUI/hesabix_ui/lib/utils/web/web_utils_stub.dart @@ -23,6 +23,11 @@ String? getLocalStorageValue(String key) => null; void setLocalStorageValue(String key, String value) {} +/// Desktop/mobile use one application window, so parked-sale storage needs no +/// browser-tab suffix. +String? getOrCreateSessionStorageValue(String key, String fallbackValue) => + null; + /// Signals the HTML boot loader to hide (web only). void notifyWebAppReady() {} @@ -33,4 +38,3 @@ void notifyWebInitProgress({ required int totalSteps, String? statusKey, }) {} - diff --git a/hesabixUI/hesabix_ui/lib/utils/web/web_utils_web.dart b/hesabixUI/hesabix_ui/lib/utils/web/web_utils_web.dart index 4af68700..0bf46dab 100755 --- a/hesabixUI/hesabix_ui/lib/utils/web/web_utils_web.dart +++ b/hesabixUI/hesabix_ui/lib/utils/web/web_utils_web.dart @@ -68,6 +68,20 @@ void setLocalStorageValue(String key, String value) { } catch (_) {} } +/// Returns a value scoped to the current browser tab. `sessionStorage` survives +/// a refresh but is not shared by separate tabs, preventing two cashiers/tabs +/// from overwriting the same parked-sales bundle. +String? getOrCreateSessionStorageValue(String key, String fallbackValue) { + try { + final current = web.window.sessionStorage.getItem(key); + if (current != null && current.isNotEmpty) return current; + web.window.sessionStorage.setItem(key, fallbackValue); + return fallbackValue; + } catch (_) { + return fallbackValue; + } +} + /// به‌روزرسانی لودر HTML در فاز init داخل Flutter (۹۶–۱۰۰٪). void notifyWebInitProgress({ required double initProgress, diff --git a/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_payment_dock.dart b/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_payment_dock.dart index 8780e07c..39906b9f 100644 --- a/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_payment_dock.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_payment_dock.dart @@ -35,6 +35,7 @@ class QuickSalesPaymentDock extends StatefulWidget { final Future Function() onConfigureChange; final String? defaultCashRegisterId; final String currencyUnit; + final int currencyId; final int decimalPlaces; final bool enabled; final VoidCallback onSave; @@ -53,6 +54,7 @@ class QuickSalesPaymentDock extends StatefulWidget { required this.onConfigureChange, required this.defaultCashRegisterId, required this.currencyUnit, + required this.currencyId, required this.decimalPlaces, required this.enabled, required this.onSave, @@ -269,6 +271,15 @@ class _QuickSalesPaymentDockState extends State { void _addPayment(QuickSalesPaymentButtonModel button) { if (!widget.enabled) return; + if (button.targetCurrencyId != null && + button.targetCurrencyId != widget.currencyId) { + SnackBarHelper.show( + context, + message: 'ارز مقصد این دکمه با ارز فاکتور یکسان نیست.', + isError: true, + ); + return; + } if (widget.payments.length >= _maxPaymentLines) { SnackBarHelper.show( context, diff --git a/hesabixUI/hesabix_ui/test/quick_sales_parked_sale_test.dart b/hesabixUI/hesabix_ui/test/quick_sales_parked_sale_test.dart index 30012f8e..d7811c86 100644 --- a/hesabixUI/hesabix_ui/test/quick_sales_parked_sale_test.dart +++ b/hesabixUI/hesabix_ui/test/quick_sales_parked_sale_test.dart @@ -5,6 +5,20 @@ import 'package:hesabix_ui/models/quick_sales_parked_sale.dart'; import 'package:hesabix_ui/models/quick_sales_change_resolution.dart'; void main() { + test('parked-sale storage is isolated by user inside one business', () { + expect( + QuickSalesParkedSalesStorage.keyFor(5, 11), + isNot(QuickSalesParkedSalesStorage.keyFor(5, 12)), + ); + }); + + test('parked-sale storage is isolated by browser-tab scope', () { + expect( + QuickSalesParkedSalesStorage.keyFor(12, 3, scope: 'tab-a'), + isNot(QuickSalesParkedSalesStorage.keyFor(12, 3, scope: 'tab-b')), + ); + }); + test('parked sale round-trips cart, customer and totals', () { final sale = QuickSalesParkedSale( id: 'sale-1', diff --git a/hesabixUI/hesabix_ui/test/quick_sales_payment_dock_test.dart b/hesabixUI/hesabix_ui/test/quick_sales_payment_dock_test.dart index 78e16c6d..a382ee18 100644 --- a/hesabixUI/hesabix_ui/test/quick_sales_payment_dock_test.dart +++ b/hesabixUI/hesabix_ui/test/quick_sales_payment_dock_test.dart @@ -50,6 +50,7 @@ void main() { onConfigureChange: () async => null, defaultCashRegisterId: '7', currencyUnit: 'ریال', + currencyId: 1, decimalPlaces: 0, enabled: true, onSave: () {}, -- 2.43.0