diff --git a/docs/quick-sales-customer-field-behavior.md b/docs/quick-sales-customer-field-behavior.md index 557281d0..33bd791a 100644 --- a/docs/quick-sales-customer-field-behavior.md +++ b/docs/quick-sales-customer-field-behavior.md @@ -64,3 +64,14 @@ API پیش از ایجاد شخص، کاندیداهای همان کسب‌وک - فراخوانی API: `hesabixUI/hesabix_ui/lib/services/customer_service.dart` - endpoint: `POST /api/v1/customers/quick-resolve` - منطق تطبیق و ایجاد: `hesabixAPI/app/services/customer_quick_entry_service.py` + +## گروه پیش‌فرض مشتری جدید + +در «تنظیمات فروش سریع» می‌توان گروه پیش‌فرض مشتریانی را تعیین کرد که با Enter از فیلد مشتری ساخته می‌شوند. گزینه «بدون گروه» رفتار پیش‌فرض و سازگار با نسخه‌های قبل است. + +- گروه فقط هنگام ایجاد واقعی یک شخص جدید اعمال می‌شود. +- انتخاب مشتری موجود، گروه او را تغییر نمی‌دهد. +- مشتری ناشناس تحت تأثیر این تنظیم نیست. +- فقط گروه فعال و متعلق به همان کسب‌وکار قابل انتخاب است. +- حذف گروه انتخاب‌شده به دلیل کلید خارجی `SET NULL` تنظیم را به «بدون گروه» برمی‌گرداند. +- قالب پیش‌فرض گروه از مسیر عادی `create_person` روی مشتری جدید اعمال می‌شود؛ نوع شخص همچنان «مشتری» باقی می‌ماند. diff --git a/hesabixAPI/adapters/db/models/quick_sales_settings.py b/hesabixAPI/adapters/db/models/quick_sales_settings.py index d8cbe372..d80e165f 100755 --- a/hesabixAPI/adapters/db/models/quick_sales_settings.py +++ b/hesabixAPI/adapters/db/models/quick_sales_settings.py @@ -43,6 +43,12 @@ class QuickSalesSetting(Base): nullable=True, comment="نام مشتری ناشناس" ) + quick_customer_group_id: Mapped[int | None] = mapped_column( + Integer, + ForeignKey("person_groups.id", ondelete="SET NULL"), + nullable=True, + comment="گروه پیش‌فرض مشتریانی که در فروش سریع ثبت می‌شوند", + ) # انبار و صندوق default_warehouse_id: Mapped[int | None] = mapped_column( @@ -186,6 +192,7 @@ class QuickSalesSetting(Base): # Relationships business = relationship("Business", backref="quick_sales_setting", uselist=False) anonymous_customer = relationship("Person", foreign_keys=[default_anonymous_customer_id]) + quick_customer_group = relationship("PersonGroup", foreign_keys=[quick_customer_group_id]) default_warehouse = relationship("Warehouse", foreign_keys=[default_warehouse_id]) default_cash_register = relationship("CashRegister", foreign_keys=[default_cash_register_id]) default_currency = relationship("Currency", foreign_keys=[default_currency_id]) diff --git a/hesabixAPI/app/services/customer_quick_entry_service.py b/hesabixAPI/app/services/customer_quick_entry_service.py index 9b6ffb77..a8103efe 100644 --- a/hesabixAPI/app/services/customer_quick_entry_service.py +++ b/hesabixAPI/app/services/customer_quick_entry_service.py @@ -13,6 +13,7 @@ from adapters.api.v1.schema_models.person import ( PersonType as PersonRequestType, ) from adapters.db.models.person import Person +from adapters.db.models.quick_sales_settings import QuickSalesSetting from app.core.responses import ApiError from app.services.person_service import create_person from app.services.telephony.phone_normalizer import normalize_iran_phone, numbers_match @@ -291,6 +292,16 @@ def resolve_or_create_quick_customer( stored_alias = cleaned_alias or normalized_mobile assert stored_alias is not None + settings = ( + db.query(QuickSalesSetting) + .filter(QuickSalesSetting.business_id == int(business_id)) + .first() + ) + quick_customer_group_id = ( + int(settings.quick_customer_group_id) + if settings is not None and settings.quick_customer_group_id is not None + else None + ) result = create_person( db, int(business_id), @@ -298,6 +309,7 @@ def resolve_or_create_quick_customer( alias_name=stored_alias, mobile=normalized_mobile, person_types=[PersonRequestType.CUSTOMER], + person_group_id=quick_customer_group_id, ), ) person_id = int(result["data"]["id"]) diff --git a/hesabixAPI/app/services/quick_sales_service.py b/hesabixAPI/app/services/quick_sales_service.py index 204cc380..3adba328 100755 --- a/hesabixAPI/app/services/quick_sales_service.py +++ b/hesabixAPI/app/services/quick_sales_service.py @@ -16,6 +16,7 @@ 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.services.person_group_service import assert_assignable_person_group from app.services.person_service import create_person logger = logging.getLogger(__name__) @@ -530,6 +531,7 @@ def get_quick_sales_settings(db: Session, business_id: int) -> Dict[str, Any]: "default_anonymous_customer_id": None, "auto_create_anonymous_customer": True, "anonymous_customer_name": "مشتری ناشناس", + "quick_customer_group_id": None, "default_warehouse_id": None, "default_cash_register_id": None, "default_currency_id": business_default_currency_id, @@ -555,6 +557,7 @@ def get_quick_sales_settings(db: Session, business_id: int) -> Dict[str, Any]: "default_anonymous_customer_id": int(obj.default_anonymous_customer_id) if obj.default_anonymous_customer_id else None, "auto_create_anonymous_customer": bool(obj.auto_create_anonymous_customer), "anonymous_customer_name": obj.anonymous_customer_name if obj.anonymous_customer_name else "مشتری ناشناس", + "quick_customer_group_id": int(obj.quick_customer_group_id) if obj.quick_customer_group_id else None, "default_warehouse_id": int(obj.default_warehouse_id) if obj.default_warehouse_id else None, "default_cash_register_id": int(obj.default_cash_register_id) if obj.default_cash_register_id else None, "default_currency_id": currency_id, @@ -612,6 +615,12 @@ def update_quick_sales_settings(db: Session, business_id: int, payload: Dict[str obj.anonymous_customer_name = str(name_data).strip() else: obj.anonymous_customer_name = None + + if "quick_customer_group_id" in payload: + group_id = payload.get("quick_customer_group_id") + if group_id is not None: + assert_assignable_person_group(db, int(business_id), int(group_id)) + obj.quick_customer_group_id = int(group_id) if group_id is not None else None if "default_warehouse_id" in payload: warehouse_id = payload.get("default_warehouse_id") diff --git a/hesabixAPI/migrations/versions/20261014_000002_quick_sales_customer_group.py b/hesabixAPI/migrations/versions/20261014_000002_quick_sales_customer_group.py new file mode 100644 index 00000000..c52b7c91 --- /dev/null +++ b/hesabixAPI/migrations/versions/20261014_000002_quick_sales_customer_group.py @@ -0,0 +1,43 @@ +"""Add the default person group for quick-created sales customers. + +Revision ID: 20261014_000002_quick_sales_customer_group +Revises: 20261014_000001_merge_tax_and_quick_sales_heads +""" + +import sqlalchemy as sa +from alembic import op + + +revision = "20261014_000002_quick_sales_customer_group" +down_revision = "20261014_000001_merge_tax_and_quick_sales_heads" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "quick_sales_settings", + sa.Column( + "quick_customer_group_id", + sa.Integer(), + nullable=True, + comment="گروه پیش‌فرض مشتریانی که در فروش سریع ثبت می‌شوند", + ), + ) + op.create_foreign_key( + "fk_quick_sales_settings_quick_customer_group_id_person_groups", + "quick_sales_settings", + "person_groups", + ["quick_customer_group_id"], + ["id"], + ondelete="SET NULL", + ) + + +def downgrade() -> None: + op.drop_constraint( + "fk_quick_sales_settings_quick_customer_group_id_person_groups", + "quick_sales_settings", + type_="foreignkey", + ) + op.drop_column("quick_sales_settings", "quick_customer_group_id") diff --git a/hesabixAPI/tests/test_customer_quick_entry_service.py b/hesabixAPI/tests/test_customer_quick_entry_service.py index 9ac3fa90..2d2b456a 100644 --- a/hesabixAPI/tests/test_customer_quick_entry_service.py +++ b/hesabixAPI/tests/test_customer_quick_entry_service.py @@ -1,5 +1,5 @@ from types import SimpleNamespace -from unittest.mock import Mock +from unittest.mock import MagicMock, Mock import pytest @@ -12,6 +12,7 @@ from app.services.customer_quick_entry_service import ( mobile_search_needles, normalize_customer_alias, normalize_customer_mobile, + resolve_or_create_quick_customer, ) @@ -163,6 +164,85 @@ def test_returns_all_similar_names_when_there_is_no_exact_match(): assert [person.id for person in matches] == [1, 2] +@pytest.mark.parametrize("configured_group_id", [None, 27]) +def test_new_quick_customer_uses_group_from_quick_sales_settings( + monkeypatch, + configured_group_id, +): + from adapters.db.models.person import Person + from adapters.db.models.quick_sales_settings import QuickSalesSetting + from app.services import customer_quick_entry_service as service + + db = MagicMock() + db.get_bind.return_value = SimpleNamespace(dialect=SimpleNamespace(name="sqlite")) + settings_query = MagicMock() + settings_query.filter.return_value.first.return_value = ( + SimpleNamespace(quick_customer_group_id=configured_group_id) + if configured_group_id is not None + else None + ) + created_person = _person(41, "مشتری جدید", mobile="09121234567") + person_query = MagicMock() + person_query.filter.return_value.one.return_value = created_person + + def query_for(model): + if model is QuickSalesSetting: + return settings_query + if model is Person: + return person_query + return MagicMock() + + db.query.side_effect = query_for + monkeypatch.setattr(service, "load_quick_customer_candidates", lambda *args, **kwargs: []) + captured_request = {} + + def fake_create_person(_db, _business_id, request): + captured_request["value"] = request + return {"data": {"id": 41}} + + monkeypatch.setattr(service, "create_person", fake_create_person) + + result = resolve_or_create_quick_customer( + db, + business_id=8, + alias_name="مشتری جدید", + mobile="09121234567", + ) + + assert result.created is True + assert result.persons == [created_person] + assert captured_request["value"].person_group_id == configured_group_id + + +def test_existing_quick_customer_keeps_its_current_group(monkeypatch): + from app.services import customer_quick_entry_service as service + + db = MagicMock() + db.get_bind.return_value = SimpleNamespace(dialect=SimpleNamespace(name="sqlite")) + existing = _person(9, "مشتری موجود", mobile="09121234567") + existing.person_group_id = 4 + monkeypatch.setattr( + service, + "load_quick_customer_candidates", + lambda *args, **kwargs: [existing], + ) + create_person = MagicMock() + monkeypatch.setattr(service, "create_person", create_person) + + result = resolve_or_create_quick_customer( + db, + business_id=8, + alias_name="مشتری موجود", + mobile="09121234567", + ) + + assert result.created is False + assert result.persons == [existing] + assert existing.person_group_id == 4 + create_person.assert_not_called() + db.query.assert_not_called() + + @pytest.mark.asyncio async def test_quick_resolve_requires_business_access(monkeypatch): from adapters.api.v1.customers import ( diff --git a/hesabixAPI/tests/test_quick_sales_service.py b/hesabixAPI/tests/test_quick_sales_service.py index d23020e0..553bd0a9 100644 --- a/hesabixAPI/tests/test_quick_sales_service.py +++ b/hesabixAPI/tests/test_quick_sales_service.py @@ -81,6 +81,68 @@ def test_get_quick_sales_settings_includes_share_defaults_when_missing_row() -> assert result["default_share_expiry_hours"] == 168 assert result["default_currency_id"] == 42 assert result["enable_stock_shortage_override"] is False + assert result["quick_customer_group_id"] is None + + +def test_update_quick_sales_settings_validates_and_saves_customer_group(monkeypatch) -> None: + from app.services import quick_sales_service as service + + db = MagicMock() + settings = MagicMock() + settings.quick_customer_group_id = None + settings_query = MagicMock() + settings_query.filter.return_value.first.return_value = settings + db.query.return_value = settings_query + validate_group = MagicMock() + monkeypatch.setattr(service, "assert_assignable_person_group", validate_group) + monkeypatch.setattr( + service, + "get_quick_sales_settings", + lambda _db, _business_id: { + "quick_customer_group_id": settings.quick_customer_group_id, + }, + ) + + result = service.update_quick_sales_settings( + db, + business_id=5, + payload={"quick_customer_group_id": 19}, + ) + + validate_group.assert_called_once_with(db, 5, 19) + assert settings.quick_customer_group_id == 19 + assert result["quick_customer_group_id"] == 19 + db.commit.assert_called_once() + + +def test_update_quick_sales_settings_can_clear_customer_group(monkeypatch) -> None: + from app.services import quick_sales_service as service + + db = MagicMock() + settings = MagicMock() + settings.quick_customer_group_id = 19 + settings_query = MagicMock() + settings_query.filter.return_value.first.return_value = settings + db.query.return_value = settings_query + validate_group = MagicMock() + monkeypatch.setattr(service, "assert_assignable_person_group", validate_group) + monkeypatch.setattr( + service, + "get_quick_sales_settings", + lambda _db, _business_id: { + "quick_customer_group_id": settings.quick_customer_group_id, + }, + ) + + result = service.update_quick_sales_settings( + db, + business_id=5, + payload={"quick_customer_group_id": None}, + ) + + validate_group.assert_not_called() + assert settings.quick_customer_group_id is None + assert result["quick_customer_group_id"] is None def test_invoice_share_link_event_type_in_seed_catalog() -> None: diff --git a/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_settings_page.dart b/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_settings_page.dart index f61eef8c..56ee6cf2 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_settings_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_settings_page.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:hesabix_ui/l10n/app_localizations.dart'; import '../../services/quick_sales_service.dart'; import '../../services/payment_gateway_service.dart'; +import '../../services/person_group_service.dart'; import '../../core/api_client.dart'; import '../../core/auth_store.dart'; import '../../utils/error_extractor.dart'; @@ -12,6 +13,7 @@ import '../../widgets/invoice/cash_register_combobox_widget.dart'; import '../../widgets/invoice/price_list_combobox_widget.dart'; import '../../widgets/banking/currency_picker_widget.dart'; import '../../models/customer_model.dart'; +import '../../models/person_group_model.dart'; import '../../widgets/business_subpage_back_leading.dart'; import '../../constants/invoice_print_paper.dart'; import '../../services/report_template_service.dart'; @@ -44,6 +46,11 @@ class _QuickSalesSettingsPageState extends State { String? _selectedCashRegisterId; int? _selectedCurrencyId; int? _selectedPriceListId; + int? _selectedQuickCustomerGroupId; + List _quickCustomerGroups = const []; + bool _loadingQuickCustomerGroups = false; + bool _quickCustomerGroupsLoadFailed = false; + String? _quickCustomerGroupsError; // Boolean settings bool _autoCreateAnonymousCustomer = true; @@ -72,6 +79,7 @@ class _QuickSalesSettingsPageState extends State { bool _loadingShareGateways = false; final _gatewayService = PaymentGatewayService(ApiClient()); + final _personGroupService = PersonGroupService(); @override void initState() { @@ -100,6 +108,7 @@ class _QuickSalesSettingsPageState extends State { _selectedCashRegisterId = settings['default_cash_register_id']?.toString(); _selectedCurrencyId = settings['default_currency_id']; _selectedPriceListId = settings['default_price_list_id']; + _selectedQuickCustomerGroupId = (settings['quick_customer_group_id'] as num?)?.toInt(); _autoPrint = settings['auto_print'] ?? false; _printPaperSize = (settings['print_paper_size'] ?? '80mm')?.toString(); _printTemplateId = (settings['print_template_id'] as num?)?.toInt(); @@ -122,6 +131,7 @@ class _QuickSalesSettingsPageState extends State { } }); + await _loadQuickCustomerGroups(); await _loadShareGateways(); await _loadPrintTemplates(); @@ -140,6 +150,41 @@ class _QuickSalesSettingsPageState extends State { } } + Future _loadQuickCustomerGroups() async { + setState(() { + _loadingQuickCustomerGroups = true; + _quickCustomerGroupsLoadFailed = false; + _quickCustomerGroupsError = null; + }); + try { + final groups = await _personGroupService.listGroups( + businessId: widget.businessId, + activeOnly: true, + rootOnly: true, + ); + if (!mounted) return; + final availableIds = groups.map((group) => group.id).toSet(); + setState(() { + _quickCustomerGroups = groups; + _loadingQuickCustomerGroups = false; + _quickCustomerGroupsLoadFailed = false; + if (_selectedQuickCustomerGroupId != null && + !availableIds.contains(_selectedQuickCustomerGroupId)) { + _selectedQuickCustomerGroupId = null; + _quickCustomerGroupsError = 'گروه ذخیره‌شده غیرفعال یا حذف شده است؛ گزینه «بدون گروه» انتخاب شد.'; + } + }); + } catch (_) { + if (!mounted) return; + setState(() { + _quickCustomerGroups = const []; + _loadingQuickCustomerGroups = false; + _quickCustomerGroupsLoadFailed = true; + _quickCustomerGroupsError = 'بارگذاری گروه‌های اشخاص انجام نشد.'; + }); + } + } + Future _loadPrintTemplates() async { setState(() => _loadingPrintTemplates = true); try { @@ -234,6 +279,7 @@ class _QuickSalesSettingsPageState extends State { ? null : _anonymousCustomerNameController.text.trim(), 'auto_create_anonymous_customer': _autoCreateAnonymousCustomer, + 'quick_customer_group_id': _selectedQuickCustomerGroupId, if (_selectedAnonymousCustomer != null) 'default_anonymous_customer_id': _selectedAnonymousCustomer!.id, if (_selectedWarehouseId != null) @@ -346,6 +392,61 @@ class _QuickSalesSettingsPageState extends State { ], ), const SizedBox(height: 24), + + _buildSection( + title: 'ثبت سریع مشتری', + icon: Icons.person_add_alt_1_outlined, + children: [ + if (_loadingQuickCustomerGroups) + const LinearProgressIndicator() + else if (_quickCustomerGroupsLoadFailed) + OutlinedButton.icon( + onPressed: _loadQuickCustomerGroups, + icon: const Icon(Icons.refresh), + label: const Text('تلاش مجدد برای بارگذاری گروه‌ها'), + ) + else + DropdownButtonFormField( + initialValue: _selectedQuickCustomerGroupId, + decoration: const InputDecoration( + labelText: 'گروه مشتریان ثبت‌شده سریع', + helperText: 'فقط مشتریان جدیدی که از فیلد مشتری فروش سریع ثبت می‌شوند در این گروه قرار می‌گیرند.', + border: OutlineInputBorder(), + ), + items: [ + const DropdownMenuItem( + value: null, + child: Text('بدون گروه'), + ), + ..._quickCustomerGroups.map( + (group) => DropdownMenuItem( + value: group.id, + child: Text(group.name, overflow: TextOverflow.ellipsis), + ), + ), + ], + onChanged: (value) { + setState(() { + _selectedQuickCustomerGroupId = value; + _quickCustomerGroupsError = null; + }); + }, + ), + if (_quickCustomerGroupsError != null) ...[ + const SizedBox(height: 8), + Text( + _quickCustomerGroupsError!, + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: cs.error), + ), + ], + const SizedBox(height: 8), + Text( + 'مشتریان موجود و مشتری ناشناس تغییر نمی‌کنند.', + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: cs.onSurfaceVariant), + ), + ], + ), + const SizedBox(height: 24), // بخش انبار و صندوق _buildSection(