diff --git a/docs/QUICK_SALES_PAYMENT_DOCK.md b/docs/QUICK_SALES_PAYMENT_DOCK.md index 5923d5d4..de720a27 100644 --- a/docs/QUICK_SALES_PAYMENT_DOCK.md +++ b/docs/QUICK_SALES_PAYMENT_DOCK.md @@ -86,7 +86,8 @@ ## نکات سازگاری - پرداخت خودکار کل مبلغ با صندوق پیش‌فرض حذف شده است؛ فاکتور جدید بدون اقدام کاربر، ردیف پرداخت ندارد. -- حالت موبایل همچنان از فرم فشرده قبلی استفاده می‌کند، ولی پرداخت بیشتر از مبلغ فاکتور و سقف ۵۰ ردیف را پشتیبانی می‌کند. +- موبایل و وب موبایل در تب «پرداخت و ثبت» همان دکمه‌های شخصی و مشترک دسکتاپ را با شبکهٔ دو ستونه نمایش می‌دهند. مبلغ پیش‌فرض ماندهٔ قابل تسویه است؛ هر لمس یک ردیف مستقل ایجاد می‌کند. ردیف‌ها به صورت کارت قابل ویرایش و حذف‌اند و تعریف، ویرایش، حذف و ترتیب دکمه‌ها از همان API مشترک استفاده می‌کند. +- رابط موبایل گزینهٔ افزودن چک ندارد و میانبرهای پرداخت در این چیدمان فعال نیستند. اسناد قدیمی یا سبدهای بازیابی‌شده حذف نمی‌شوند. اضافه‌دریافت، سقف ۵۰ ردیف، اشتراک‌گذاری مانده و دکمه‌های ثابت ثبت حفظ شده‌اند. - قابلیت اشتراک‌گذاری مانده فاکتور در ستون اطلاعات سند دسکتاپ حفظ شده است. - اگر ساخت خودکار سند دریافت در تنظیمات غیرفعال باشد، نوار دکمه‌های پرداخت نمایش داده نمی‌شود و رفتار قبلی اشتراک‌گذاری و ثبت باقی می‌ماند. diff --git a/docs/QUICK_SALES_STOCK_SHORTAGE_WORKFLOW.md b/docs/QUICK_SALES_STOCK_SHORTAGE_WORKFLOW.md index 56da44fb..01f565dd 100644 --- a/docs/QUICK_SALES_STOCK_SHORTAGE_WORKFLOW.md +++ b/docs/QUICK_SALES_STOCK_SHORTAGE_WORKFLOW.md @@ -8,6 +8,10 @@ ## رفتار کاربر در فروش سریع +در ثبت غیرهم‌زمان، فروش ناموفق در سبدهای پارک‌شده حفظ می‌شود و نوار «بررسی کسری» نمایش داده می‌شود. رسیدگی با انتخاب کاربر و برای همان سبد انجام می‌شود؛ نتیجهٔ فروش قبلی وسط کار روی فروش بعدی، پنجرهٔ تصمیم‌گیری باز نمی‌کند. چند کسری در صف نگه داشته می‌شوند. پنجرهٔ فهرست کسری و علت ثبت منفی قابل اسکرول است تا روی گوشی و با کیبورد باز قابل استفاده بماند. گزینهٔ ثبت منفی برای کسری کالای یونیک/سریالی در رابط نیز نمایش داده نمی‌شود. + +بازگشت از تنظیمات، سیاست کسری و مجوز نمایش گزینه‌ها را تازه می‌کند. سبد جاری، مشتری مشخص، پرداخت‌ها، ارز، انبار و انتخاب‌های تسویه حفظ می‌شوند و پیش‌فرض‌های جدید برای فروش تازه استفاده خواهند شد. + API همهٔ اقلام دارای کسری را در یک پاسخ `409 / INSUFFICIENT_STOCK` برمی‌گرداند. دیالوگ فروش سریع نام کالا، انبار، موجودی قابل استفاده و مقدار موردنیاز را نمایش می‌دهد و این انتخاب‌ها را ارائه می‌کند: 1. **انصراف**: فاکتور و موجودی تغییری نمی‌کند. diff --git a/docs/quick-sales-customer-field-behavior.md b/docs/quick-sales-customer-field-behavior.md index 01fff0d4..fcb82fef 100644 --- a/docs/quick-sales-customer-field-behavior.md +++ b/docs/quick-sales-customer-field-behavior.md @@ -17,6 +17,8 @@ ## فوکوس و متن موقت +در موبایل و وب موبایل، پنجرهٔ انتخاب مشتری فضای کیبورد را لحاظ می‌کند و محتوای آن قابل اسکرول است. علاوه بر Enter، دکمهٔ «یافتن / ثبت و انتخاب» همان مسیر تطبیق و ثبت سریع را اجرا می‌کند. تا رسیدن پاسخ، وضعیت انتظار نمایش داده می‌شود و ارسال دوباره از دکمه مسدود است. راهنمای نام/موبایل و نحوهٔ گروه‌بندی مشتری جدید در همان پنجره دیده می‌شود. نام مشتری منتخب نیز در تب پرداخت و ثبت با دکمهٔ تغییر مشتری نمایش داده می‌شود. + با اولین فوکوس روی فیلد، کل نام مشتری فعلی انتخاب می‌شود تا اولین حرف یا رقم، متن قبلی را جایگزین کند. کلیک بعدی در همان وضعیت فوکوس همچنان اجازه می‌دهد مکان‌نما در نقطه دلخواه قرار بگیرد. متنی که کاربر تایپ می‌کند تا زمان انتخاب یا ثبت سریع، پیش‌نویس محلی است. تایپ عادی مشتری فعلی فاکتور را به مشتری ناشناس تغییر نمی‌دهد. تنها انتخاب صریح از فهرست یا پاسخ موفق ثبت سریع، مشتری فاکتور را تغییر می‌دهد. 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 ed515c54..59ed618d 100755 --- a/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_page.dart +++ b/hesabixUI/hesabix_ui/lib/pages/business/quick_sales_page.dart @@ -36,8 +36,8 @@ import '../../models/quick_sales_parked_sale.dart'; import '../../models/quick_sales_change_resolution.dart'; import '../../widgets/invoice/customer_combobox_widget.dart'; import '../../widgets/quick_sales/quick_sales_parked_sales_bar.dart'; -import '../../widgets/quick_sales/quick_sales_payment_composer.dart'; import '../../widgets/quick_sales/quick_sales_payment_dock.dart'; +import '../../widgets/quick_sales/quick_sales_stock_shortage_dialog.dart'; import '../../widgets/quick_sales/quick_sales_change_resolution_dialog.dart'; import '../../widgets/invoice/warehouse_combobox_widget.dart'; import '../../utils/currency_display_utils.dart'; @@ -306,6 +306,9 @@ class _QuickSalesPageState extends State final List _sales = []; String _activeSaleId = ''; final Set _pendingQuickSaleRequestIds = {}; + final Map job, bool shouldPrint})> + _deferredStockShortages = {}; + bool _reviewingStockShortage = false; final Completer _parkedSalesHydratedCompleter = Completer(); bool _parkedHydrated = false; Timer? _parkedPersistDebounce; @@ -402,21 +405,21 @@ class _QuickSalesPageState extends State } if (failed.isNotEmpty && mounted) { - Map? firstStockShortageJob; - String? firstStockShortageSaleId; for (final job in failed) { final requestId = job['request_id']?.toString(); if (requestId != null && requestId.isNotEmpty) { final saleId = _markQueuedSaleFailed(requestId, notify: false); final details = job['error_details']; final shortages = details is Map ? details['shortages'] : null; - if (firstStockShortageJob == null && - job['error_code'] == 'INSUFFICIENT_STOCK' && + if (job['error_code'] == 'INSUFFICIENT_STOCK' && saleId != null && shortages is List && shortages.isNotEmpty) { - firstStockShortageJob = job; - firstStockShortageSaleId = saleId; + await _handleQueuedStockShortage( + saleId: saleId, + job: job, + shouldPrint: false, + ); } } } @@ -428,13 +431,6 @@ class _QuickSalesPageState extends State : 'یک فروش قبلی ثبت نشد: $message', isError: true, ); - if (firstStockShortageJob != null && firstStockShortageSaleId != null) { - await _handleQueuedStockShortage( - saleId: firstStockShortageSaleId, - job: firstStockShortageJob, - shouldPrint: false, - ); - } } for (final job in completed) { @@ -633,7 +629,13 @@ class _QuickSalesPageState extends State _invoiceCurrencyRoundMonetary = rm; } - Future _loadSettings() async { + Future _loadSettings({bool preserveSale = false}) async { + final savedSale = preserveSale && !_isActiveSaleBlank + ? _snapshotActiveSale() + : null; + final wasAnonymous = _isAnonymousSelected; + final savedCurrencyId = _defaultCurrencyId; + final savedPriceListId = _defaultPriceListId; setState(() { _loading = true; }); @@ -683,8 +685,20 @@ class _QuickSalesPageState extends State }); try { - await _hydrateParkedSalesIntoFields(); + if (preserveSale) { + if (savedSale != null) { + _applySaleState(savedSale); + if (wasAnonymous) _selectedCustomer = _anonymousCustomer; + _defaultWarehouseId = savedSale.warehouseId; + _selectedCashRegisterId = savedSale.cashRegisterId; + _defaultCurrencyId = savedCurrencyId; + _defaultPriceListId = savedPriceListId; + } + } else { + await _hydrateParkedSalesIntoFields(); + } } catch (_) { + if (preserveSale) rethrow; _activeSaleId = QuickSalesParkedSale.newId(); _sales.clear(); _captureActiveSaleIntoList(); @@ -905,6 +919,11 @@ class _QuickSalesPageState extends State _checkoutDiscountExpanded = false; _selectedCashRegisterId = _settingsDefaultCashRegisterId; _defaultWarehouseId = _settingsDefaultWarehouseId; + _defaultCurrencyId = + _settings?['default_currency_id'] ?? + widget.authStore.currentBusiness?.defaultCurrency?.id; + _defaultPriceListId = _settings?['default_price_list_id']; + _applyCurrencyMetaFromCache(); _documentDate = DateTime.now(); _documentDescriptionController.clear(); _globalDiscountType = 'percent'; @@ -989,6 +1008,7 @@ class _QuickSalesPageState extends State final completedSaleId = _activeSaleId; final newSaleId = QuickSalesParkedSale.newId(); setState(() { + _deferredStockShortages.remove(completedSaleId); _activeSaleId = newSaleId; _applyBlankSaleState(); _saveAction = _QuickSalesSaveAction.none; @@ -1015,6 +1035,7 @@ class _QuickSalesPageState extends State _captureActiveSaleIntoList(); final newSaleId = QuickSalesParkedSale.newId(); setState(() { + _deferredStockShortages.remove(requestId); _activeSaleId = newSaleId; _applyBlankSaleState(); _saveAction = _QuickSalesSaveAction.none; @@ -1131,6 +1152,7 @@ class _QuickSalesPageState extends State final wasActive = id == _activeSaleId; setState(() { + _deferredStockShortages.remove(id); _sales.removeWhere((s) => s.id == id); if (_sales.isEmpty) { if (_activeSaleId.isEmpty) { @@ -1199,25 +1221,42 @@ class _QuickSalesPageState extends State } Widget _withParkedSalesBar(Widget child, {required bool compact}) { - if (!_shouldShowParkedSalesBar) return child; + if (!_shouldShowParkedSalesBar && _deferredStockShortages.isEmpty) { + return child; + } final t = AppLocalizations.of(context); return Column( children: [ - QuickSalesParkedSalesBar( - sales: _parkedSaleChipData(t), - compact: compact, - enabled: !_isSaving, - newSaleEnabled: - !_isActiveSaleBlank && _sales.length < _maxParkedSales, - newSaleLabel: t.quickSalesParkedNewSale, - newSaleTooltip: _isActiveSaleBlank - ? t.quickSalesParkedNewSaleAlreadyEmpty - : t.quickSalesParkedNewSaleTooltip, - discardTooltip: t.quickSalesParkedDiscardTooltip, - onNewSale: _startNewSale, - onSelect: _selectParkedSale, - onDiscard: (id) => unawaited(_discardParkedSale(id)), - ), + if (_deferredStockShortages.isNotEmpty) + MaterialBanner( + content: Text( + '${_deferredStockShortages.length} فروش با کسری موجودی منتظر بررسی است؛ سبدها محفوظ‌اند.', + ), + actions: [ + TextButton( + onPressed: _isSaving || _reviewingStockShortage + ? null + : () => unawaited(_reviewDeferredStockShortage()), + child: const Text('بررسی کسری'), + ), + ], + ), + if (_shouldShowParkedSalesBar) + QuickSalesParkedSalesBar( + sales: _parkedSaleChipData(t), + compact: compact, + enabled: !_isSaving, + newSaleEnabled: + !_isActiveSaleBlank && _sales.length < _maxParkedSales, + newSaleLabel: t.quickSalesParkedNewSale, + newSaleTooltip: _isActiveSaleBlank + ? t.quickSalesParkedNewSaleAlreadyEmpty + : t.quickSalesParkedNewSaleTooltip, + discardTooltip: t.quickSalesParkedDiscardTooltip, + onNewSale: _startNewSale, + onSelect: _selectParkedSale, + onDiscard: (id) => unawaited(_discardParkedSale(id)), + ), Expanded(child: child), ], ); @@ -2676,86 +2715,35 @@ class _QuickSalesPageState extends State List> shortages, { bool correctionAlreadyApplied = false, }) { - final canOverride = - _enableStockShortageOverride && - widget.authStore.hasBusinessPermission( - 'inventory', - 'negative_stock_override', - ); - final canCorrect = - _enableStockShortageOverride && - widget.authStore.hasBusinessPermission('goods_expense_income', 'add') && - widget.authStore.hasBusinessPermission('goods_expense_income', 'post'); return showDialog<_StockShortageAction>( context: context, barrierDismissible: false, - builder: (dialogContext) => AlertDialog( - title: const Text('کسری موجودی'), - content: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 560), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text( - 'موجودی سیستمی کالاهای زیر برای ثبت فاکتور کافی نیست:', - ), - const SizedBox(height: 12), - ...shortages.map((item) { - final name = item['product_name'] ?? 'کالا'; - final warehouse = item['warehouse_name']; - final available = item['available_quantity'] ?? 0; - final requested = item['requested_quantity'] ?? 0; - return ListTile( - dense: true, - contentPadding: EdgeInsets.zero, - title: Text(name.toString()), - subtitle: Text( - '${warehouse == null ? '' : '$warehouse — '}موجودی: $available، موردنیاز: $requested', - ), - ); - }), - if (!_enableStockShortageOverride) - const Padding( - padding: EdgeInsets.only(top: 8), - child: Text( - 'گردش‌کار کسری موجودی در تنظیمات فروش سریع فعال نیست.', - ), - ), - if (correctionAlreadyApplied) - const Padding( - padding: EdgeInsets.only(top: 8), - child: Text( - 'اصلاح موجودی این فروش قبلاً ثبت شده است؛ برای جلوگیری از ثبت سند تکراری، اصلاح دوباره در دسترس نیست.', - ), - ), - ], - ), + builder: (dialogContext) => QuickSalesStockShortageDialog( + shortages: shortages, + saleLabel: + '${_selectedCustomer?.name ?? 'مشتری ناشناس'} — ${_cartItems.length} قلم', + workflowEnabled: _enableStockShortageOverride, + canOverride: widget.authStore.hasBusinessPermission( + 'inventory', + 'negative_stock_override', ), - actions: [ - TextButton( - onPressed: () => - Navigator.pop(dialogContext, _StockShortageAction.cancel), - child: const Text('انصراف'), - ), - TextButton( - onPressed: () => - Navigator.pop(dialogContext, _StockShortageAction.park), - child: const Text('پارک فروش'), - ), - if (canCorrect && !correctionAlreadyApplied) - OutlinedButton( - onPressed: () => - Navigator.pop(dialogContext, _StockShortageAction.correct), - child: const Text('اصلاح موجودی'), + canCorrect: + widget.authStore.hasBusinessPermission( + 'goods_expense_income', + 'add', + ) && + widget.authStore.hasBusinessPermission( + 'goods_expense_income', + 'post', ), - if (canOverride) - FilledButton( - onPressed: () => - Navigator.pop(dialogContext, _StockShortageAction.override), - child: const Text('ثبت با موجودی منفی'), - ), - ], + correctionAlreadyApplied: correctionAlreadyApplied, + onCancel: () => + Navigator.pop(dialogContext, _StockShortageAction.cancel), + onPark: () => Navigator.pop(dialogContext, _StockShortageAction.park), + onCorrect: () => + Navigator.pop(dialogContext, _StockShortageAction.correct), + onOverride: () => + Navigator.pop(dialogContext, _StockShortageAction.override), ), ); } @@ -2767,11 +2755,13 @@ class _QuickSalesPageState extends State context: context, builder: (dialogContext) => StatefulBuilder( builder: (context, setDialogState) => AlertDialog( + scrollable: true, title: const Text('ثبت یک‌باره با موجودی منفی'), content: Column( mainAxisSize: MainAxisSize.min, children: [ DropdownButtonFormField( + isExpanded: true, value: reason, decoration: const InputDecoration(labelText: 'علت'), items: const [ @@ -2832,6 +2822,7 @@ class _QuickSalesPageState extends State final confirmed = await showDialog( context: context, builder: (dialogContext) => AlertDialog( + scrollable: true, title: const Text('اصلاح موجودی'), content: const Text( 'این گزینه «کالای درآمدشده» را با همان تاریخ فاکتور ثبت می‌کند. فقط وقتی ادامه دهید که کالا واقعاً در انبار موجود است و خرید، انتقال یا موجودی اول دوره‌ای از قلم نیفتاده باشد.', @@ -3306,6 +3297,37 @@ class _QuickSalesPageState extends State required String saleId, required Map job, required bool shouldPrint, + }) async { + if (!mounted) return; + setState(() { + _deferredStockShortages[saleId] = (job: job, shouldPrint: shouldPrint); + }); + } + + Future _reviewDeferredStockShortage() async { + if (_isSaving || + _reviewingStockShortage || + _deferredStockShortages.isEmpty) { + return; + } + if (ModalRoute.of(context)?.isCurrent != true) return; + final entry = _deferredStockShortages.entries.first; + setState(() => _reviewingStockShortage = true); + try { + await _resolveQueuedStockShortage( + saleId: entry.key, + job: entry.value.job, + shouldPrint: entry.value.shouldPrint, + ); + } finally { + if (mounted) setState(() => _reviewingStockShortage = false); + } + } + + Future _resolveQueuedStockShortage({ + required String saleId, + required Map job, + required bool shouldPrint, }) async { final shortagesValue = job['error_details'] is Map ? (job['error_details'] as Map)['shortages'] @@ -3322,6 +3344,10 @@ class _QuickSalesPageState extends State // correction/override workflow. The failed request already has a new ID, // so any retry gets a fresh idempotency key. _selectParkedSale(saleId); + if (_activeSaleId != saleId) { + setState(() => _deferredStockShortages.remove(saleId)); + return; + } final correctionAlreadyApplied = (job['error_details'] as Map?)?['stock_correction_already_applied'] == true; @@ -3340,6 +3366,7 @@ class _QuickSalesPageState extends State if (!mounted || action == null || action == _StockShortageAction.cancel) { return; } + setState(() => _deferredStockShortages.remove(saleId)); if (action == _StockShortageAction.park) { _startNewSale(); return; @@ -4045,6 +4072,9 @@ class _QuickSalesPageState extends State } bool _handleKeyEvent(KeyEvent event) { + if (_reviewingStockShortage || ModalRoute.of(context)?.isCurrent != true) { + return false; + } if (event is KeyDownEvent) { final isControlPressed = HardwareKeyboard.instance.isControlPressed; final isMetaPressed = HardwareKeyboard.instance.isMetaPressed; @@ -4161,6 +4191,9 @@ class _QuickSalesPageState extends State authStore: widget.authStore, isRequired: false, enableQuickCreateOnSubmit: true, + quickCreateHint: _settings?['quick_customer_group_id'] == null + ? 'مشتری جدید بدون گروه ثبت می‌شود؛ نام، موبایل یا هر دو را وارد کنید.' + : 'مشتری جدید در گروه پیش‌فرض فروش سریع ثبت می‌شود؛ نام، موبایل یا هر دو را وارد کنید.', dense: dense, label: 'مشتری', hintText: 'مشتری ناشناس', @@ -4630,15 +4663,26 @@ class _QuickSalesPageState extends State tooltip: 'پاک کردن سبد (Ctrl+K)', onPressed: _clearCart, ), - IconButton( - icon: const Icon(Icons.settings), - tooltip: 'تنظیمات', - onPressed: () { - context.push( - '/business/${widget.businessId}/settings/quick-sales', - ); - }, - ), + if (widget.authStore.hasBusinessPermission('settings', 'business') || + widget.authStore.hasBusinessPermission( + 'quick_sales', + 'manage_default_payment_shortcuts', + )) + IconButton( + icon: const Icon(Icons.settings), + tooltip: 'تنظیمات', + onPressed: _isSaving + ? null + : () async { + final router = GoRouter.of(context); + await _persistParkedSalesNow(); + if (!mounted) return; + await router.push( + '/business/${widget.businessId}/settings/quick-sales', + ); + if (mounted) await _loadSettings(preserveSale: true); + }, + ), ], ), bottomNavigationBar: null, @@ -5616,6 +5660,17 @@ class _QuickSalesPageState extends State child: ListView( padding: const EdgeInsets.fromLTRB(12, 8, 12, 8), children: [ + ListTile( + contentPadding: EdgeInsets.zero, + leading: const Icon(Icons.person_outline), + title: Text(_selectedCustomer?.name ?? 'مشتری ناشناس'), + trailing: TextButton( + onPressed: _isSaving + ? null + : () => _mobileTabController.animateTo(1), + child: const Text('تغییر مشتری'), + ), + ), _buildCheckoutScrollBody( cs, includeCustomer: false, @@ -6305,25 +6360,27 @@ class _QuickSalesPageState extends State ), const SizedBox(height: 8), if (_autoCreatePaymentDocument) ...[ - QuickSalesPaymentComposer( + QuickSalesPaymentDock( key: ValueKey(_activeSaleId), + mobile: true, businessId: widget.businessId, payments: _payments, - onChanged: _onPaymentsChanged, - cashFollowsTotal: _cashFollowsTotal, - onCashFollowsTotalChanged: (v) { - if (v == _cashFollowsTotal) return; - setState(() => _cashFollowsTotal = v); + onChanged: (payments) { + _cashFollowsTotal = false; + _onPaymentsChanged(payments); }, - invoiceTotal: _paymentTargetAmount, + invoiceTotal: _totalAmount, + paymentTarget: _paymentTargetAmount, + changeResolution: _validChangeResolution, + onConfigureChange: _openChangeResolutionDialog, defaultCashRegisterId: _selectedCashRegisterId, enabled: !_isSaving, - currencyId: _defaultCurrencyId, + currencyId: _defaultCurrencyId!, currencyUnit: _paymentCurrencyUnit, decimalPlaces: _invoiceCurrencyDecimalPlaces, authStore: widget.authStore, - calendarController: widget.calendarController, - isAnonymousCustomer: _isAnonymousSelected, + onSave: () => _saveInvoice(print: false), + onSaveAndPrint: () => _saveInvoice(print: true), ), if (_isOverpaid) ...[ const SizedBox(height: 8), 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 e08ea61e..83cd742d 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 @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:hesabix_ui/l10n/app_localizations.dart'; import '../../services/quick_sales_service.dart'; +import '../../services/customer_service.dart'; import '../../services/payment_gateway_service.dart'; import '../../services/person_group_service.dart'; import '../../core/api_client.dart'; @@ -18,6 +19,7 @@ import '../../widgets/business_subpage_back_leading.dart'; import '../../widgets/quick_sales/quick_sales_default_shortcuts_dialog.dart'; import '../../constants/invoice_print_paper.dart'; import '../../services/report_template_service.dart'; +import '../../utils/responsive_helper.dart'; class QuickSalesSettingsPage extends StatefulWidget { final int businessId; @@ -110,8 +112,15 @@ class _QuickSalesSettingsPageState extends State { } try { final settings = await _service.getSettings(businessId: widget.businessId); + final anonymousId = (settings['default_anonymous_customer_id'] as num?)?.toInt(); + final anonymousCustomer = anonymousId == null ? null + : await CustomerService(ApiClient()).getCustomerById( + businessId: widget.businessId, customerId: anonymousId); + if (!mounted) return; setState(() { _settings = settings; + _selectedAnonymousCustomer = anonymousCustomer ?? (anonymousId == null ? null + : Customer(id: anonymousId, name: 'مشتری #$anonymousId')); _anonymousCustomerNameController.text = settings['anonymous_customer_name'] ?? 'مشتری ناشناس'; _autoCreateAnonymousCustomer = settings['auto_create_anonymous_customer'] ?? true; _selectedWarehouseId = settings['default_warehouse_id']; @@ -142,19 +151,17 @@ class _QuickSalesSettingsPageState extends State { }); await _loadQuickCustomerGroups(); + if (!mounted) return; await _loadShareGateways(); + if (!mounted) return; await _loadPrintTemplates(); - - // بارگذاری مشتری ناشناس اگر وجود دارد - if (settings['default_anonymous_customer_id'] != null) { - // TODO: بارگذاری اطلاعات مشتری - } } catch (e) { + if (!mounted) return; setState(() { _error = ErrorExtractor.forContext(e, context); }); } finally { - setState(() { + if (mounted) setState(() { _loading = false; }); } @@ -295,21 +302,17 @@ class _QuickSalesSettingsPageState extends State { }); try { final payload = { - 'anonymous_customer_name': _anonymousCustomerNameController.text.trim().isEmpty - ? null + 'anonymous_customer_name': + _anonymousCustomerNameController.text.trim().isEmpty + ? 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) - 'default_warehouse_id': _selectedWarehouseId, - if (_selectedCashRegisterId != null) - 'default_cash_register_id': int.tryParse(_selectedCashRegisterId!), - if (_selectedCurrencyId != null) - 'default_currency_id': _selectedCurrencyId, - if (_selectedPriceListId != null) - 'default_price_list_id': _selectedPriceListId, + 'default_anonymous_customer_id': _selectedAnonymousCustomer?.id, + 'default_warehouse_id': _selectedWarehouseId, + 'default_cash_register_id': int.tryParse(_selectedCashRegisterId ?? ''), + 'default_currency_id': _selectedCurrencyId, + 'default_price_list_id': _selectedPriceListId, 'auto_print': _autoPrint, 'print_paper_size': _printPaperSize, 'print_template_id': _printTemplateId, @@ -321,29 +324,30 @@ class _QuickSalesSettingsPageState extends State { 'auto_create_payment_document': _autoCreatePaymentDocument, 'show_purchase_price': _showPurchasePrice, 'default_share_online_payment': _defaultShareOnlinePayment, - if (_defaultShareGatewayId != null) 'default_share_gateway_id': _defaultShareGatewayId, + 'default_share_gateway_id': _defaultShareGatewayId, 'default_share_channels': _buildShareChannelsPayload(), 'default_share_expiry_hours': _defaultShareExpiryHours, }; - + final saved = await _service.updateSettings( businessId: widget.businessId, payload: payload, ); + if (!mounted) return; setState(() { _settings = saved; }); - if (!mounted) return; final t = AppLocalizations.of(context); SnackBarHelper.show(context, message: t.savedSuccessfully); } catch (e) { - setState(() { - _error = ErrorExtractor.forContext(e, context); - }); + if (!mounted) return; + SnackBarHelper.showError(context, message: ErrorExtractor.forContext(e, context)); } finally { - setState(() { - _saving = false; - }); + if (mounted) { + setState(() { + _saving = false; + }); + } } } @@ -351,6 +355,7 @@ class _QuickSalesSettingsPageState extends State { Widget build(BuildContext context) { final t = AppLocalizations.of(context); final cs = Theme.of(context).colorScheme; + final compact = ResponsiveHelper.isShellCompactWidth(context); return Scaffold( appBar: AppBar( @@ -359,6 +364,41 @@ class _QuickSalesSettingsPageState extends State { backgroundColor: cs.surface, foregroundColor: cs.onSurface, ), + bottomNavigationBar: + compact && _canManageGeneralSettings && !_loading && _settings != null + ? Material( + elevation: 3, + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + Expanded( + child: FilledButton.icon( + onPressed: _saving ? null : _save, + icon: _saving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Icon(Icons.save), + label: Text(t.save), + ), + ), + TextButton( + onPressed: _saving ? null : _load, + child: Text(t.reload), + ), + ], + ), + ), + ), + ) + : null, body: _loading ? const Center(child: CircularProgressIndicator()) : _error != null @@ -381,7 +421,7 @@ class _QuickSalesSettingsPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (_canManageDefaultShortcuts) ...[ + if (_canManageDefaultShortcuts && !compact) ...[ _buildDefaultShortcutsSection(), const SizedBox(height: 24), ], @@ -745,7 +785,11 @@ class _QuickSalesSettingsPageState extends State { const SizedBox(height: 24), // دکمه‌های ذخیره - Align( + if (_canManageDefaultShortcuts && compact) ...[ + _buildDefaultShortcutsSection(), + const SizedBox(height: 24), + ], + if (!compact) Align( alignment: AlignmentDirectional.centerEnd, child: Wrap( spacing: 8, @@ -920,14 +964,25 @@ class _QuickSalesSettingsPageState extends State { required List children, }) { final cs = Theme.of(context).colorScheme; - + if (ResponsiveHelper.isShellCompactWidth(context)) { + return Card( + margin: EdgeInsets.zero, + child: ExpansionTile( + key: PageStorageKey('quick-sales-settings-$title'), + leading: Icon(icon), + title: Text(title), + childrenPadding: const EdgeInsets.all(12), + expandedCrossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ); + } + return Card( margin: EdgeInsets.zero, elevation: 1, color: cs.surfaceContainerHighest, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), child: Padding( padding: const EdgeInsets.all(16), child: Column( @@ -937,12 +992,14 @@ class _QuickSalesSettingsPageState extends State { children: [ Icon(icon, color: cs.primary, size: 24), const SizedBox(width: 12), - Text( - title, - style: TextStyle( - fontSize: 18, - fontWeight: FontWeight.w600, - color: cs.onSurface, + Expanded( + child: Text( + title, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + color: cs.onSurface, + ), ), ), ], diff --git a/hesabixUI/hesabix_ui/lib/widgets/invoice/customer_combobox_widget.dart b/hesabixUI/hesabix_ui/lib/widgets/invoice/customer_combobox_widget.dart index 2f66411b..ca31788e 100755 --- a/hesabixUI/hesabix_ui/lib/widgets/invoice/customer_combobox_widget.dart +++ b/hesabixUI/hesabix_ui/lib/widgets/invoice/customer_combobox_widget.dart @@ -59,6 +59,8 @@ class CustomerComboboxWidget extends StatefulWidget { final bool showFinancialBalance; final bool dense; final bool enableQuickCreateOnSubmit; + final String? quickCreateHint; + final CustomerService? service; const CustomerComboboxWidget({ super.key, @@ -72,6 +74,8 @@ class CustomerComboboxWidget extends StatefulWidget { this.showFinancialBalance = false, this.dense = false, this.enableQuickCreateOnSubmit = false, + this.quickCreateHint, + this.service, }); @override @@ -79,7 +83,9 @@ class CustomerComboboxWidget extends StatefulWidget { } class _CustomerComboboxWidgetState extends State { - final CustomerService _customerService = CustomerService(ApiClient()); + late final CustomerService _customerService = + widget.service ?? CustomerService(ApiClient()); + final ValueNotifier _quickResolvingNotifier = ValueNotifier(false); final TextEditingController _searchController = TextEditingController(); Timer? _debounceTimer; List _customers = []; @@ -165,6 +171,7 @@ class _CustomerComboboxWidgetState extends State { _overlayScrollController.dispose(); _searchController.dispose(); _pickerStateNotifier.dispose(); + _quickResolvingNotifier.dispose(); super.dispose(); } @@ -684,6 +691,7 @@ class _CustomerComboboxWidgetState extends State { // invalidates the response. Focus loss and display restoration do not. final requestGeneration = ++_searchGeneration; setState(() => _isQuickResolving = true); + _quickResolvingNotifier.value = true; _desktopOverlayEntry?.markNeedsBuild(); try { final result = await _customerService.quickResolveCustomer( @@ -750,6 +758,7 @@ class _CustomerComboboxWidgetState extends State { } finally { if (mounted) { setState(() => _isQuickResolving = false); + _quickResolvingNotifier.value = false; _desktopOverlayEntry?.markNeedsBuild(); } } @@ -861,6 +870,9 @@ class _CustomerComboboxWidgetState extends State { onSubmitted: () => unawaited(_submitField()), onLoadMore: _loadMoreCustomers, onAddNew: () => _addNewPerson(bottomSheetContext), + quickCreateEnabled: widget.enableQuickCreateOnSubmit, + quickCreateHint: widget.quickCreateHint, + resolving: _quickResolvingNotifier, ); }, ).whenComplete(() => _mobilePickerOpen = false); @@ -1137,6 +1149,9 @@ class _CustomerComboboxWidgetState extends State { } class _CustomerPickerBottomSheet extends StatefulWidget { + final bool quickCreateEnabled; + final String? quickCreateHint; + final ValueNotifier resolving; final ValueNotifier<_CustomerPickerState> pickerStateNotifier; final Customer? selectedCustomer; final Function(Customer) onCustomerSelected; @@ -1155,6 +1170,9 @@ class _CustomerPickerBottomSheet extends StatefulWidget { required this.onSubmitted, required this.onLoadMore, this.onAddNew, + required this.quickCreateEnabled, + this.quickCreateHint, + required this.resolving, }); @override @@ -1194,85 +1212,147 @@ class _CustomerPickerBottomSheetState Widget build(BuildContext context) { final theme = Theme.of(context); - return Container( - height: MediaQuery.of(context).size.height * 0.7, - padding: const EdgeInsets.all(16), - child: Column( - children: [ - Row( - children: [ - Text( - 'انتخاب طرف حساب', - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - const Spacer(), - if (widget.onAddNew != null) - IconButton( - onPressed: widget.onAddNew, - icon: const Icon(Icons.add), - tooltip: 'افزودن شخص جدید', - color: theme.colorScheme.primary, - ), - IconButton( - onPressed: () => Navigator.pop(context), - icon: const Icon(Icons.close), - ), - ], - ), - const SizedBox(height: 16), - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: TextField( - controller: widget.searchController, - focusNode: _searchFocus, - selectAllOnFocus: true, - decoration: InputDecoration( - hintText: 'جست‌وجو در طرف حساب‌ها...', - prefixIcon: const Icon(Icons.search), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(8), + final media = MediaQuery.of(context); + return Padding( + padding: EdgeInsets.only(bottom: media.viewInsets.bottom), + child: SafeArea( + top: false, + child: SizedBox( + height: + (media.size.height * 0.9 - + media.viewInsets.bottom - + media.padding.bottom) + .clamp(0.0, media.size.height), + child: ValueListenableBuilder( + valueListenable: widget.resolving, + builder: (context, resolving, _) => Container( + padding: const EdgeInsets.all(16), + child: CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + Row( + children: [ + Expanded( + child: Text( + 'انتخاب طرف حساب', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + if (widget.onAddNew != null) + IconButton( + onPressed: resolving ? null : widget.onAddNew, + icon: const Icon(Icons.add), + tooltip: 'افزودن شخص جدید', + color: theme.colorScheme.primary, + ), + IconButton( + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.close), + ), + ], + ), + const SizedBox(height: 16), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextField( + controller: widget.searchController, + focusNode: _searchFocus, + selectAllOnFocus: true, + textInputAction: TextInputAction.search, + onEditingComplete: () {}, + decoration: InputDecoration( + hintText: widget.quickCreateEnabled + ? 'نام، موبایل یا هر دو' + : 'جست‌وجو در طرف حساب‌ها...', + prefixIcon: const Icon(Icons.search), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + onChanged: widget.onSearchChanged, + onSubmitted: (_) { + if (!resolving) widget.onSubmitted(); + }, + ), + ), + SizedBox( + width: 40, + height: kMinInteractiveDimension, + child: + ValueListenableBuilder<_CustomerPickerState>( + valueListenable: widget.pickerStateNotifier, + builder: (context, pickerState, _) { + if (!pickerState.isLoading && + !resolving) { + return const SizedBox.shrink(); + } + return const Padding( + padding: EdgeInsetsDirectional.only( + start: 8, + top: 12, + ), + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ), + ); + }, + ), + ), + ], + ), + if (widget.quickCreateEnabled) ...[ + const SizedBox(height: 8), + if (widget.quickCreateHint != null) + Text( + widget.quickCreateHint!, + style: theme.textTheme.bodySmall, + ), + FilledButton.icon( + onPressed: resolving ? null : widget.onSubmitted, + icon: resolving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Icon(Icons.person_add_alt_1), + label: Text( + resolving + ? 'در حال یافتن / ثبت مشتری…' + : 'یافتن / ثبت و انتخاب', + ), + ), + ], + const SizedBox(height: 16), + ], ), ), - onChanged: widget.onSearchChanged, - onSubmitted: (_) => widget.onSubmitted(), - ), + SliverFillRemaining( + hasScrollBody: true, + child: ValueListenableBuilder<_CustomerPickerState>( + valueListenable: widget.pickerStateNotifier, + builder: (context, pickerState, _) { + return _buildCustomersList(context, pickerState); + }, + ), + ), + ], ), - SizedBox( - width: 40, - height: kMinInteractiveDimension, - child: ValueListenableBuilder<_CustomerPickerState>( - valueListenable: widget.pickerStateNotifier, - builder: (context, pickerState, _) { - if (!pickerState.isLoading) { - return const SizedBox.shrink(); - } - return const Padding( - padding: EdgeInsetsDirectional.only(start: 8, top: 12), - child: SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ); - }, - ), - ), - ], - ), - const SizedBox(height: 16), - Expanded( - child: ValueListenableBuilder<_CustomerPickerState>( - valueListenable: widget.pickerStateNotifier, - builder: (context, pickerState, _) { - return _buildCustomersList(context, pickerState); - }, ), ), - ], + ), ), ); } @@ -1290,25 +1370,27 @@ class _CustomerPickerBottomSheetState } if (pickerState.customers.isEmpty) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon( - Icons.person_off, - size: 48, - color: colorScheme.onSurface.withValues(alpha: 0.5), - ), - const SizedBox(height: 16), - Text( - pickerState.hasSearched - ? 'طرف حسابی یافت نشد' - : 'هیچ طرف حسابی ثبت نشده است', - style: theme.textTheme.bodyLarge?.copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.7), + return SingleChildScrollView( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.person_off, + size: 48, + color: colorScheme.onSurface.withValues(alpha: 0.5), ), - ), - ], + const SizedBox(height: 16), + Text( + pickerState.hasSearched + ? 'طرف حسابی یافت نشد' + : 'هیچ طرف حسابی ثبت نشده است', + style: theme.textTheme.bodyLarge?.copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.7), + ), + ), + ], + ), ), ); } 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 39906b9f..c0882cb9 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 @@ -42,6 +42,9 @@ class QuickSalesPaymentDock extends StatefulWidget { final VoidCallback onSaveAndPrint; final QuickSalesService? service; + /// Inline layout for the mobile checkout tab; the page owns save actions. + final bool mobile; + const QuickSalesPaymentDock({ super.key, required this.businessId, @@ -60,6 +63,7 @@ class QuickSalesPaymentDock extends StatefulWidget { required this.onSave, required this.onSaveAndPrint, this.service, + this.mobile = false, }); @override @@ -89,7 +93,9 @@ class _QuickSalesPaymentDockState extends State { double _buttonWidth = _defaultButtonWidth; bool _expanded = false; - String? get _activeShortcutPlatform => kIsWeb + String? get _activeShortcutPlatform => widget.mobile + ? null + : kIsWeb ? 'web' : defaultTargetPlatform == TargetPlatform.windows ? 'windows' @@ -136,8 +142,10 @@ class _QuickSalesPaymentDockState extends State { }); _syncAmount(); unawaited(_loadButtons()); - unawaited(_loadWidth()); - unawaited(_loadExpanded()); + if (!widget.mobile) { + unawaited(_loadWidth()); + unawaited(_loadExpanded()); + } } @override @@ -378,6 +386,7 @@ class _QuickSalesPaymentDockState extends State { @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; + if (widget.mobile) return _buildMobile(cs); return LayoutBuilder( builder: (context, constraints) { if (constraints.maxWidth < 1050) { @@ -548,6 +557,101 @@ class _QuickSalesPaymentDockState extends State { ); } + Widget _buildMobile(ColorScheme cs) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Card( + margin: EdgeInsets.zero, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _SummaryValue( + label: 'قابل تسویه', + value: _format(widget.paymentTarget), + ), + _SummaryValue(label: 'پرداخت‌شده', value: _format(_paid)), + _SummaryValue(label: 'مانده', value: _format(_remaining)), + ], + ), + ), + ), + SizedBox(height: 300, child: _buildAmountAndButtons(cs)), + if (widget.payments.isEmpty) + const Padding( + padding: EdgeInsets.all(12), + child: Text('هنوز پرداختی ثبت نشده است'), + ), + for (final payment in widget.payments) + Card( + key: ValueKey('mobile-payment-${payment.id}'), + margin: const EdgeInsets.only(bottom: 8), + child: Padding( + padding: const EdgeInsets.all(10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Icon( + _paymentIcon(payment.type), + color: _paymentColor(payment.type, cs), + ), + const SizedBox(width: 8), + Expanded(child: Text(_paymentTitle(payment))), + IconButton( + tooltip: 'حذف پرداخت', + color: cs.error, + onPressed: widget.enabled + ? () => _removePayment(payment.id) + : null, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + Text(_formatPaymentDate(payment.transactionDate)), + const SizedBox(height: 8), + TextFormField( + key: ValueKey('payment-${payment.id}'), + initialValue: formatNumberForInput( + payment.amount, + decimalPlaces: widget.decimalPlaces, + ), + enabled: widget.enabled, + textDirection: TextDirection.ltr, + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + inputFormatters: [ + const EnglishDigitsFormatter(), + ThousandsSeparatorInputFormatter( + allowDecimal: widget.decimalPlaces > 0, + ), + ], + decoration: InputDecoration( + labelText: 'مبلغ', + suffixText: widget.currencyUnit, + border: const OutlineInputBorder(), + ), + onChanged: (raw) { + final amount = parseFormattedNumber(raw); + if (amount != null && amount > _epsilon) { + _updatePaymentAmount(payment, raw); + } + }, + onFieldSubmitted: (raw) => + _updatePaymentAmount(payment, raw), + ), + ], + ), + ), + ), + ], + ); + } + Widget _buildCompact(ColorScheme cs) { return Column( children: [ @@ -774,7 +878,7 @@ class _QuickSalesPaymentDockState extends State { border: const OutlineInputBorder(), ), ), - if (_change > 0) + if (_change > 0 && !widget.mobile) Padding( padding: const EdgeInsets.only(top: 6), child: InkWell( @@ -828,13 +932,19 @@ class _QuickSalesPaymentDockState extends State { thumbVisibility: _buttons.length > 6, child: GridView.builder( controller: _buttonScroll, - gridDelegate: - const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 122, - mainAxisExtent: 66, - crossAxisSpacing: 8, - mainAxisSpacing: 8, - ), + gridDelegate: widget.mobile + ? const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisExtent: 84, + crossAxisSpacing: 8, + mainAxisSpacing: 8, + ) + : const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 122, + mainAxisExtent: 66, + crossAxisSpacing: 8, + mainAxisSpacing: 8, + ), itemCount: _buttons.length + 1, itemBuilder: (context, index) { if (index == _buttons.length) { @@ -871,7 +981,10 @@ class _QuickSalesPaymentDockState extends State { onEdit: button.isSystem ? null : () => _openEditor(existing: button), - onShortcut: () => _openShortcutEditor(button), + onShortcut: widget.mobile + ? null + : () => _openShortcutEditor(button), + showShortcut: !widget.mobile, onDelete: button.isSystem ? null : () => _deleteButton(button), @@ -1128,6 +1241,7 @@ class _SummaryValue extends StatelessWidget { } class _PaymentTargetTile extends StatelessWidget { + final bool showShortcut; final QuickSalesPaymentButtonModel button; final IconData icon; final bool enabled; @@ -1148,6 +1262,7 @@ class _PaymentTargetTile extends StatelessWidget { this.onDelete, this.onMoveBefore, this.onMoveAfter, + this.showShortcut = true, }); @override @@ -1167,13 +1282,15 @@ class _PaymentTargetTile extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, ), - if (button.shortcutForPlatform(kIsWeb ? 'web' : 'windows') != - null) + if (showShortcut && + button.shortcutForPlatform(kIsWeb ? 'web' : 'windows') != + null) Text( '${kIsWeb ? 'وب' : 'ویندوز'}: ${button.shortcutForPlatform(kIsWeb ? 'web' : 'windows')!}', style: Theme.of(context).textTheme.labelSmall, ), - if (button.shortcutProfile(kIsWeb ? 'web' : 'windows').conflict) + if (showShortcut && + button.shortcutProfile(kIsWeb ? 'web' : 'windows').conflict) Text( 'تداخل میانبر', style: Theme.of(context).textTheme.labelSmall?.copyWith( @@ -1193,6 +1310,7 @@ class _PaymentTargetTile extends StatelessWidget { top: 0, end: 0, child: PopupMenuButton( + enabled: enabled, padding: EdgeInsets.zero, iconSize: 17, tooltip: 'مدیریت دکمه', diff --git a/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_stock_shortage_dialog.dart b/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_stock_shortage_dialog.dart new file mode 100644 index 00000000..2f78bbd8 --- /dev/null +++ b/hesabixUI/hesabix_ui/lib/widgets/quick_sales/quick_sales_stock_shortage_dialog.dart @@ -0,0 +1,101 @@ +import 'package:flutter/material.dart'; + +/// Scrollable on phones, including when a sale contains many shortage lines. +class QuickSalesStockShortageDialog extends StatelessWidget { + final List> shortages; + final String? saleLabel; + final bool workflowEnabled; + final bool canOverride; + final bool canCorrect; + final bool correctionAlreadyApplied; + final VoidCallback onCancel; + final VoidCallback onPark; + final VoidCallback onCorrect; + final VoidCallback onOverride; + + const QuickSalesStockShortageDialog({ + super.key, + required this.shortages, + this.saleLabel, + required this.workflowEnabled, + required this.canOverride, + required this.canCorrect, + this.correctionAlreadyApplied = false, + required this.onCancel, + required this.onPark, + required this.onCorrect, + required this.onOverride, + }); + + bool get _hasUnique => shortages.any( + (item) => + item['inventory_mode']?.toString().trim().toLowerCase() == 'unique', + ); + + @override + Widget build(BuildContext context) { + return AlertDialog( + scrollable: true, + title: const Text('کسری موجودی'), + content: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (saleLabel != null) + Text( + 'فروش: $saleLabel', + style: const TextStyle(fontWeight: FontWeight.w700), + ), + const Text('موجودی سیستمی کالاهای زیر برای ثبت فاکتور کافی نیست:'), + const SizedBox(height: 12), + for (final item in shortages) + ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text('${item['product_name'] ?? 'کالا'}'), + subtitle: Text( + '${item['warehouse_name'] ?? 'انبار'} — موجودی: ${item['available_quantity'] ?? 0}، موردنیاز: ${item['requested_quantity'] ?? 0}، کسری: ${item['shortage_quantity'] ?? '—'}', + ), + ), + if (!workflowEnabled) + const Text( + 'گردش‌کار کسری موجودی در تنظیمات فروش سریع فعال نیست.', + ), + if (_hasUnique) + const Text( + 'ثبت موجودی منفی برای کالای یونیک/سریالی مجاز نیست؛ سریال و گردش واقعی انبار را بررسی کنید.', + ), + if (workflowEnabled && !canOverride && !_hasUnique) + const Text( + 'برای ثبت یک‌باره موجودی منفی، مجوز مربوط به موجودی منفی لازم است.', + ), + if (workflowEnabled && !canCorrect) + const Text( + 'اصلاح موجودی به مجوز ایجاد و قطعی‌کردن سند کالای درآمدشده نیاز دارد.', + ), + if (correctionAlreadyApplied) + const Text( + 'اصلاح موجودی این فروش قبلاً ثبت شده است؛ برای جلوگیری از ثبت سند تکراری، اصلاح دوباره در دسترس نیست.', + ), + ], + ), + ), + actions: [ + TextButton(onPressed: onCancel, child: const Text('انصراف')), + TextButton(onPressed: onPark, child: const Text('پارک فروش')), + if (workflowEnabled && canCorrect && !correctionAlreadyApplied) + OutlinedButton( + onPressed: onCorrect, + child: const Text('اصلاح موجودی'), + ), + if (workflowEnabled && canOverride && !_hasUnique) + FilledButton( + onPressed: onOverride, + child: const Text('ثبت با موجودی منفی'), + ), + ], + ); + } +} diff --git a/hesabixUI/hesabix_ui/test/quick_sales_mobile_customer_test.dart b/hesabixUI/hesabix_ui/test/quick_sales_mobile_customer_test.dart new file mode 100644 index 00000000..6ed6c962 --- /dev/null +++ b/hesabixUI/hesabix_ui/test/quick_sales_mobile_customer_test.dart @@ -0,0 +1,92 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hesabix_ui/core/api_client.dart'; +import 'package:hesabix_ui/core/auth_store.dart'; +import 'package:hesabix_ui/models/customer_model.dart'; +import 'package:hesabix_ui/services/customer_service.dart'; +import 'package:hesabix_ui/widgets/invoice/customer_combobox_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _CustomerService extends CustomerService { + _CustomerService() : super(ApiClient()); + final result = Completer>(); + int creates = 0; + String? receivedMobile; + + @override + Future> searchCustomers({ + required int businessId, + String? searchQuery, + int page = 1, + int limit = 20, + }) async => {'customers': [], 'hasMore': false}; + + @override + Future> quickResolveCustomer({ + required int businessId, + String? aliasName, + String? mobile, + }) { + creates++; + receivedMobile = mobile; + return result.future; + } +} + +void main() { + testWidgets( + 'mobile customer submit works with keyboard and blocks duplicate taps', + (tester) async { + SharedPreferences.setMockInitialValues({}); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(320, 640); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetViewInsets); + final service = _CustomerService(); + Customer? selected; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomerComboboxWidget( + businessId: 5, + authStore: AuthStore(), + enableQuickCreateOnSubmit: true, + quickCreateHint: 'ثبت در گروه پیش‌فرض', + service: service, + onCustomerChanged: (value) => selected = value, + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byType(InkWell).first); + await tester.pumpAndSettle(); + tester.view.viewInsets = const FakeViewPadding(bottom: 260); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), '09121234567 علی رضایی'); + await tester.pump(const Duration(milliseconds: 500)); + await tester.ensureVisible(find.text('یافتن / ثبت و انتخاب')); + await tester.tap(find.text('یافتن / ثبت و انتخاب')); + await tester.pump(); + expect(service.creates, 1); + expect(service.receivedMobile, '09121234567'); + expect(find.text('در حال یافتن / ثبت مشتری…'), findsOneWidget); + final button = tester.widget(find.byType(FilledButton)); + expect(button.onPressed, isNull); + expect(tester.takeException(), isNull); + service.result.complete({ + 'created': true, + 'customers': [ + const Customer(id: 42, name: 'علی رضایی', phone: '09121234567'), + ], + }); + await tester.pumpAndSettle(); + expect(selected?.id, 42); + expect(find.text('یافتن / ثبت و انتخاب'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); +} 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 a382ee18..16ad127f 100644 --- a/hesabixUI/hesabix_ui/test/quick_sales_payment_dock_test.dart +++ b/hesabixUI/hesabix_ui/test/quick_sales_payment_dock_test.dart @@ -8,13 +8,102 @@ import 'package:hesabix_ui/widgets/quick_sales/quick_sales_payment_dock.dart'; import 'package:shared_preferences/shared_preferences.dart'; class _FakeQuickSalesService extends QuickSalesService { + final List buttons; + + _FakeQuickSalesService({this.buttons = const []}); + @override Future> listPaymentButtons({ required int businessId, - }) async => const []; + }) async => buttons; } void main() { + for (final width in [320.0, 390.0]) { + testWidgets('mobile payments split and delete at width $width', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + await tester.binding.setSurfaceSize(Size(width, 850)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final buttons = [ + for (final target in ['cash_register', 'bank', 'person']) + QuickSalesPaymentButtonModel.fromJson({ + 'id': target, + 'business_id': 4952, + 'scope': 'user', + 'target_type': target, + 'target_id': 7, + 'target_currency_id': 1, + 'target_name': target, + 'label': target, + }), + ]; + var payments = []; + await tester.pumpWidget( + MaterialApp( + home: Directionality( + textDirection: TextDirection.rtl, + child: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + return SingleChildScrollView( + child: QuickSalesPaymentDock( + mobile: true, + businessId: 4952, + authStore: AuthStore(), + payments: payments, + onChanged: (value) => setState(() => payments = value), + invoiceTotal: 10000000, + paymentTarget: 10000000, + changeResolution: null, + onConfigureChange: () async => null, + defaultCashRegisterId: '7', + currencyUnit: 'ریال', + currencyId: 1, + decimalPlaces: 0, + enabled: true, + onSave: () {}, + onSaveAndPrint: () {}, + service: _FakeQuickSalesService(buttons: buttons), + ), + ); + }, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect( + payments, + isEmpty, + ); // No automatic cash receipt on opening checkout. + expect(find.text('چک'), findsNothing); + expect(find.text('person'), findsOneWidget); + final amountField = find.widgetWithText(TextField, 'مبلغ پرداخت'); + await tester.enterText(amountField, '4000000'); + await tester.tap(find.text('cash_register')); + await tester.pumpAndSettle(); + expect(payments.single.amount, 4000000); + expect(payments.single.type, TransactionType.cashRegister); + final field = tester.widget(amountField); + expect(field.controller!.text.replaceAll(',', ''), '6000000'); + await tester.tap(find.text('bank')); + await tester.pumpAndSettle(); + expect(payments, hasLength(2)); + expect(payments.last.amount, 6000000); + expect(payments.last.type, TransactionType.bank); + expect(tester.takeException(), isNull); + await tester.ensureVisible(find.byTooltip('حذف پرداخت').last); + await tester.tap(find.byTooltip('حذف پرداخت').last); + await tester.pumpAndSettle(); + expect(payments, hasLength(1)); + expect(field.controller!.text.replaceAll(',', ''), '6000000'); + expect(tester.takeException(), isNull); + }); + } + testWidgets('desktop payment panel collapses without hiding fixed summary', ( tester, ) async { diff --git a/hesabixUI/hesabix_ui/test/quick_sales_stock_shortage_dialog_test.dart b/hesabixUI/hesabix_ui/test/quick_sales_stock_shortage_dialog_test.dart new file mode 100644 index 00000000..425c716b --- /dev/null +++ b/hesabixUI/hesabix_ui/test/quick_sales_stock_shortage_dialog_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hesabix_ui/widgets/quick_sales/quick_sales_stock_shortage_dialog.dart'; + +void main() { + for (final unique in [false, true]) { + testWidgets('phone shortage dialog scrolls many lines; unique=$unique', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(320, 568)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + var parked = false; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => QuickSalesStockShortageDialog( + shortages: [ + for (var i = 0; i < 30; i++) + { + 'product_name': 'کالای $i', + 'inventory_mode': unique ? 'unique' : 'bulk', + 'warehouse_name': 'انبار فروشگاه', + 'available_quantity': 0, + 'requested_quantity': 2, + 'shortage_quantity': 2, + }, + ], + workflowEnabled: true, + canOverride: true, + canCorrect: true, + correctionAlreadyApplied: true, + onCancel: () {}, + onPark: () => parked = true, + onCorrect: () {}, + onOverride: () {}, + ), + ), + child: const Text('بازکردن'), + ), + ), + ), + ), + ); + await tester.tap(find.text('بازکردن')); + await tester.pumpAndSettle(); + expect( + find.text('ثبت با موجودی منفی'), + unique ? findsNothing : findsOneWidget, + ); + expect(find.text('اصلاح موجودی'), findsNothing); + expect(tester.takeException(), isNull); + await tester.drag( + find.byType(SingleChildScrollView).first, + const Offset(0, -4000), + ); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('پارک فروش')); + await tester.tap(find.text('پارک فروش')); + expect(parked, isTrue); + expect(tester.takeException(), isNull); + }); + } +}