forked from hesabix/arc
7392 lines
273 KiB
Dart
Executable file
7392 lines
273 KiB
Dart
Executable file
import 'dart:async';
|
||
import 'dart:convert';
|
||
import 'package:dio/dio.dart' as dio;
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:flutter/foundation.dart';
|
||
import 'package:share_plus/share_plus.dart';
|
||
import 'package:shared_preferences/shared_preferences.dart';
|
||
import '../../services/quick_sales_service.dart';
|
||
import '../../services/invoice_service.dart';
|
||
import '../../services/payment_gateway_service.dart';
|
||
import '../../services/product_service.dart';
|
||
import '../../services/warehouse_service.dart';
|
||
import '../../services/price_list_service.dart';
|
||
import '../../services/category_service.dart';
|
||
import '../../core/api_client.dart';
|
||
import '../../constants/invoice_print_paper.dart';
|
||
import '../../core/auth_store.dart';
|
||
import '../../core/hesabix_back.dart';
|
||
import '../../core/calendar_controller.dart';
|
||
import '../../utils/error_extractor.dart';
|
||
import '../../utils/snackbar_helper.dart';
|
||
import '../../utils/number_normalizer.dart' as number_utils;
|
||
import '../../utils/number_formatters.dart';
|
||
import '../../utils/product_search_overlay_policy.dart';
|
||
import '../../utils/invoice_global_discount_calculator.dart';
|
||
import '../../utils/quick_sales_customer_balance.dart';
|
||
import '../../utils/quick_sales_stock_correction.dart';
|
||
import '../../l10n/app_localizations.dart';
|
||
import '../../services/business_api_service.dart';
|
||
import '../../services/currency_service.dart';
|
||
import '../../models/invoice_line_item.dart';
|
||
import '../../models/invoice_transaction.dart';
|
||
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_change_resolution_dialog.dart';
|
||
import '../../widgets/invoice/warehouse_combobox_widget.dart';
|
||
import '../../utils/currency_display_utils.dart';
|
||
import '../../widgets/permission/access_denied_page.dart';
|
||
import '../../widgets/product/product_form_dialog.dart';
|
||
import '../../widgets/product/category_tree_widget.dart';
|
||
import '../../widgets/date_input_field.dart';
|
||
import '../../models/customer_model.dart';
|
||
import 'package:go_router/go_router.dart';
|
||
import 'business_shell_side_nav_scope.dart';
|
||
import '../../widgets/barcode/mobile_barcode_scan_screen.dart';
|
||
import '../../constants/frequent_description_scope.dart';
|
||
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';
|
||
|
||
/// کد کسبوکاری برای نمایش در فروش سریع: اگر [code] با [id] یکی باشد، از `product_code`، `tax_code` یا اولین بارکد عمومی استفاده میشود.
|
||
String? _quickSalesDisplayProductBusinessCode(Map<String, dynamic> p) {
|
||
final idRaw = p['id'];
|
||
final idStr = idRaw == null
|
||
? ''
|
||
: number_utils.toEnglishDigits(idRaw.toString().trim());
|
||
|
||
bool looksLikeInternalIdOnly(String v) {
|
||
final t = v.trim();
|
||
if (t.isEmpty) return true;
|
||
if (idStr.isEmpty) return false;
|
||
final tNorm = number_utils.toEnglishDigits(t);
|
||
return tNorm == idStr;
|
||
}
|
||
|
||
final code = (p['code']?.toString() ?? '').trim();
|
||
final productCode = (p['product_code']?.toString() ?? '').trim();
|
||
final tax = (p['tax_code']?.toString() ?? '').trim();
|
||
final tokens = parseGeneralBarcodeTokens(p['general_barcodes']?.toString());
|
||
final gb0 = tokens.isNotEmpty ? tokens.first.trim() : '';
|
||
|
||
for (final candidate in [code, productCode, tax, gb0]) {
|
||
if (!looksLikeInternalIdOnly(candidate)) return candidate;
|
||
}
|
||
if (code.isNotEmpty) return code;
|
||
if (productCode.isNotEmpty) return productCode;
|
||
if (tax.isNotEmpty) return tax;
|
||
return null;
|
||
}
|
||
|
||
/// نوع عملیات ثبت در حال اجرا (برای لودینگ دقیق روی دکمهها).
|
||
enum _QuickSalesSaveAction { none, save, saveAndPrint }
|
||
|
||
enum _StockShortageAction { cancel, park, correct, override }
|
||
|
||
class _QuickSalesShareSnapshot {
|
||
static const empty = _QuickSalesShareSnapshot(
|
||
onlinePaymentEnabled: false,
|
||
hasGateways: false,
|
||
gatewayId: null,
|
||
expiryHours: 168,
|
||
sendSms: false,
|
||
sendEmail: false,
|
||
useNativeShare: false,
|
||
customerName: '',
|
||
customerMobile: null,
|
||
customerEmail: null,
|
||
);
|
||
|
||
final bool onlinePaymentEnabled;
|
||
final bool hasGateways;
|
||
final int? gatewayId;
|
||
final int expiryHours;
|
||
final bool sendSms;
|
||
final bool sendEmail;
|
||
final bool useNativeShare;
|
||
final String customerName;
|
||
final String? customerMobile;
|
||
final String? customerEmail;
|
||
|
||
const _QuickSalesShareSnapshot({
|
||
required this.onlinePaymentEnabled,
|
||
required this.hasGateways,
|
||
required this.gatewayId,
|
||
required this.expiryHours,
|
||
required this.sendSms,
|
||
required this.sendEmail,
|
||
required this.useNativeShare,
|
||
required this.customerName,
|
||
required this.customerMobile,
|
||
required this.customerEmail,
|
||
});
|
||
}
|
||
|
||
class QuickSalesPage extends StatefulWidget {
|
||
final int businessId;
|
||
final AuthStore authStore;
|
||
final CalendarController calendarController;
|
||
|
||
/// اگر از لانچر موبایل باز شده؛ دکمهٔ عقب و اَندروید به این مسیر میرود.
|
||
final String? mobileLauncherHomePath;
|
||
|
||
const QuickSalesPage({
|
||
super.key,
|
||
required this.businessId,
|
||
required this.authStore,
|
||
required this.calendarController,
|
||
this.mobileLauncherHomePath,
|
||
});
|
||
|
||
@override
|
||
State<QuickSalesPage> createState() => _QuickSalesPageState();
|
||
}
|
||
|
||
class _QuickSalesPageState extends State<QuickSalesPage>
|
||
with SingleTickerProviderStateMixin {
|
||
/// نمایشگرهای خیلی باریک (مثلاً آیفون ۶ ~۳۷۵pt، SE قدیمی ~۳۲۰pt)
|
||
static const double _compactBreakpoint = 400.0;
|
||
final QuickSalesService _quickSalesService = QuickSalesService();
|
||
final InvoiceService _invoiceService = InvoiceService();
|
||
final PaymentGatewayService _paymentGatewayService = PaymentGatewayService(
|
||
ApiClient(),
|
||
);
|
||
final ProductService _productService = ProductService();
|
||
final WarehouseService _warehouseService = WarehouseService();
|
||
final PriceListService _priceListService = PriceListService(
|
||
apiClient: ApiClient(),
|
||
);
|
||
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<String, dynamic>? _settings;
|
||
Customer? _anonymousCustomer;
|
||
|
||
// سبد خرید
|
||
List<InvoiceLineItem> _cartItems = [];
|
||
|
||
// موجودی محصولات (productId -> stock)
|
||
Map<int, num> _productStocks = {};
|
||
final Set<int> _loadingStockProductIds = <int>{};
|
||
final Set<int> _pendingStockProductIds = <int>{};
|
||
bool _loadingStocksBulk = false;
|
||
Timer? _stockBatchTimer;
|
||
|
||
// کش قیمت لیست قیمت (per session)
|
||
final Map<int, num?> _priceListCache = <int, num?>{};
|
||
|
||
// جستجو / افزودن به سبد
|
||
bool _barcodeSearching = false;
|
||
int? _addingProductId;
|
||
int? _recentProductLoadingId;
|
||
|
||
// تاریخچه محصولات اخیر
|
||
List<Map<String, dynamic>> _recentProducts = [];
|
||
static const String _recentProductsKey = 'quick_sales_recent_products';
|
||
static const int _maxRecentProducts = 10;
|
||
|
||
// مشتری
|
||
Customer? _selectedCustomer;
|
||
num? _customerBalance;
|
||
String? _customerBalanceStatus;
|
||
bool _customerBalanceLoading = false;
|
||
String? _customerBalanceError;
|
||
bool _applyCustomerBalance = false;
|
||
int _customerBalanceRequestGeneration = 0;
|
||
|
||
// پرداخت
|
||
List<InvoiceTransaction> _payments = [];
|
||
QuickSalesChangeResolution? _changeResolution;
|
||
String? _selectedCashRegisterId;
|
||
bool _autoCreatePaymentDocument = true;
|
||
bool _cashFollowsTotal = false;
|
||
bool _shareRemainingEnabled = false;
|
||
|
||
// اشتراکگذاری (وقتی سند دریافت ثبت نمیشود)
|
||
bool _shareOnlinePaymentEnabled = true;
|
||
int? _shareGatewayId;
|
||
bool _shareSendSms = true;
|
||
bool _shareSendEmail = false;
|
||
bool _shareViaNativeShare = true;
|
||
int _shareExpiryHours = 168;
|
||
List<Map<String, dynamic>> _shareGateways = const [];
|
||
bool _loadingShareGateways = false;
|
||
|
||
// تنظیمات
|
||
int? _defaultWarehouseId;
|
||
int? _defaultCurrencyId;
|
||
List<Map<String, dynamic>>? _businessCurrenciesCache;
|
||
int _invoiceCurrencyDecimalPlaces = 2;
|
||
bool _invoiceCurrencyRoundMonetary = true;
|
||
int? _defaultPriceListId;
|
||
bool _autoPrint = false;
|
||
bool _enableWarehouseDocument = true;
|
||
String _warehouseDocumentType = 'posted'; // 'draft' or 'posted'
|
||
bool _showInventory = true;
|
||
bool _enableStockShortageOverride = false;
|
||
bool _showPurchasePrice = false;
|
||
int? _printTemplateId;
|
||
String? _printPaperSize = '80mm';
|
||
|
||
// تاریخ و شرح سند فاکتور
|
||
DateTime _documentDate = DateTime.now();
|
||
final TextEditingController _documentDescriptionController =
|
||
TextEditingController();
|
||
|
||
InvoiceGlobalDiscountPolicy _globalDiscountPolicy =
|
||
const InvoiceGlobalDiscountPolicy();
|
||
String _globalDiscountType = 'percent';
|
||
late final TextEditingController _globalDiscountValueController;
|
||
|
||
// جستجوی محصول
|
||
final TextEditingController _barcodeController = TextEditingController();
|
||
final FocusNode _barcodeFocus = FocusNode();
|
||
final FocusNode _keyboardListenerFocus = FocusNode();
|
||
final LayerLink _barcodeFieldLayerLink = LayerLink();
|
||
final ScrollController _barcodeOverlayScrollController = ScrollController();
|
||
OverlayEntry? _barcodeOverlayEntry;
|
||
List<Map<String, dynamic>> _barcodeSuggestions =
|
||
const <Map<String, dynamic>>[];
|
||
bool _barcodeSuggestionsLoading = false;
|
||
bool _barcodeSuggestionsLoadingMore = false;
|
||
bool _barcodeSuggestionsHasMore = false;
|
||
int _barcodeSuggestionsSkip = 0;
|
||
String _barcodeSuggestionsQuery = '';
|
||
int _barcodeHighlightedIndex = -1;
|
||
bool _barcodeSuggestionNavigatedByKeyboard = false;
|
||
int _barcodeSuggestionRequestGeneration = 0;
|
||
|
||
/// جلوگیری از دوبار اجرا شدن انتخاب با دابلکلیک روی همان ردیف اورلی پیشنهادها.
|
||
DateTime? _lastOverlaySuggestionTapAt;
|
||
int? _lastOverlaySuggestionTapProductId;
|
||
|
||
late final TabController _mobileTabController;
|
||
int _mobileTabIndex = 0;
|
||
final Set<int> _mobileTabsBuilt = <int>{0};
|
||
Timer? _searchDebounce;
|
||
Timer? _globalDiscountDebounce;
|
||
String?
|
||
_lastFailedSearchQuery; // آخرین جستجوی ناموفق برای نمایش دکمه افزودن کالا
|
||
|
||
/// همسو با API (`products.add`)؛ بدون این مجوز نباید دیالوگ افزودن کالا باز شود.
|
||
bool get _canCreateProducts =>
|
||
widget.authStore.hasBusinessPermission('products', 'add');
|
||
|
||
// دستهبندیها
|
||
List<CategoryNode> _categoryTree = [];
|
||
bool _loadingCategories = false;
|
||
int? _selectedCategoryId;
|
||
|
||
VoidCallback? _restoreDesktopRailAfterQuit;
|
||
|
||
/// پیشفرض تنظیمات (نه مقدار فعلی فروش باز) برای فروش جدید.
|
||
int? _settingsDefaultWarehouseId;
|
||
String? _settingsDefaultCashRegisterId;
|
||
bool _settingsAutoCreatePaymentDocument = true;
|
||
|
||
static const int _maxParkedSales = 12;
|
||
final List<QuickSalesParkedSale> _sales = [];
|
||
String _activeSaleId = '';
|
||
final Set<String> _pendingQuickSaleRequestIds = <String>{};
|
||
final Completer<void> _parkedSalesHydratedCompleter = Completer<void>();
|
||
bool _parkedHydrated = false;
|
||
Timer? _parkedPersistDebounce;
|
||
bool _checkoutDiscountExpanded = false;
|
||
|
||
@override
|
||
void setState(VoidCallback fn) {
|
||
super.setState(fn);
|
||
if (_parkedHydrated && mounted) {
|
||
_schedulePersistParkedSales();
|
||
}
|
||
}
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_mobileTabController = TabController(
|
||
length: 3,
|
||
vsync: this,
|
||
initialIndex: _mobileTabIndex,
|
||
);
|
||
_mobileTabController.addListener(_onMobileTabChanged);
|
||
_globalDiscountValueController = TextEditingController();
|
||
_globalDiscountValueController.addListener(() {
|
||
_globalDiscountDebounce?.cancel();
|
||
_globalDiscountDebounce = Timer(const Duration(milliseconds: 120), () {
|
||
if (mounted) setState(() {});
|
||
});
|
||
});
|
||
_documentDescriptionController.addListener(_onParkedSaleDescriptionChanged);
|
||
_loadSettings();
|
||
_loadRecentProducts();
|
||
_barcodeFocus.addListener(_onBarcodeFocusChanged);
|
||
_barcodeOverlayScrollController.addListener(_onBarcodeOverlayScroll);
|
||
// فوکوس خودکار روی فیلد بارکد
|
||
// فوکوس خودکار روی فیلد بارکد؛ در حالت ریل دسکتاپ فضای بیشتر با جمع شدن نوار کناری
|
||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||
if (!mounted) return;
|
||
final shellScope = BusinessShellSideNavScope.readMaybeOf(context);
|
||
if (shellScope?.canControlDesktopRail ?? false) {
|
||
shellScope!.setRailVisible(false);
|
||
final scope = shellScope;
|
||
_restoreDesktopRailAfterQuit = () => scope.setRailVisible(true);
|
||
}
|
||
_barcodeFocus.requestFocus();
|
||
unawaited(_resumePendingQuickSaleJobs());
|
||
});
|
||
}
|
||
|
||
Future<void> _resumePendingQuickSaleJobs() async {
|
||
try {
|
||
await _parkedSalesHydratedCompleter.future;
|
||
if (!mounted || !_parkedHydrated) return;
|
||
final jobs = await _invoiceService.listQuickSaleInvoiceJobs(
|
||
businessId: widget.businessId,
|
||
);
|
||
if (!mounted || _isSaving) return;
|
||
|
||
final pending = jobs
|
||
.where(
|
||
(job) => job['status'] == 'queued' || job['status'] == 'processing',
|
||
)
|
||
.toList();
|
||
final failed = jobs.where((job) => job['status'] == 'failed').toList();
|
||
final completed = jobs
|
||
.where((job) => job['status'] == 'completed')
|
||
.toList();
|
||
|
||
if (pending.isNotEmpty) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'${pending.length} فروش قبلی هنوز در حال ثبت است؛ وضعیتشان پیگیری میشود.',
|
||
);
|
||
for (final job in pending) {
|
||
final requestId = job['request_id']?.toString();
|
||
if (requestId == null || requestId.isEmpty) continue;
|
||
final alreadyTracked = !_pendingQuickSaleRequestIds.add(requestId);
|
||
if (_activeSaleId == requestId) {
|
||
_openBlankSaleAfterQueuedSave(requestId);
|
||
}
|
||
if (alreadyTracked) continue;
|
||
unawaited(
|
||
_watchQuickSaleInvoiceJob(
|
||
requestId: requestId,
|
||
personId: 0,
|
||
totalAmount: 0,
|
||
shouldPrint: false,
|
||
shouldShare: false,
|
||
shareSnapshot: _QuickSalesShareSnapshot.empty,
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
if (failed.isNotEmpty && mounted) {
|
||
Map<String, dynamic>? 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' &&
|
||
saleId != null &&
|
||
shortages is List &&
|
||
shortages.isNotEmpty) {
|
||
firstStockShortageJob = job;
|
||
firstStockShortageSaleId = saleId;
|
||
}
|
||
}
|
||
}
|
||
final message = failed.first['error_message']?.toString().trim();
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: message == null || message.isEmpty
|
||
? 'یکی از فروشهای قبلی ثبت نشده است؛ سبد را بررسی و دوباره ثبت کنید.'
|
||
: 'یک فروش قبلی ثبت نشد: $message',
|
||
isError: true,
|
||
);
|
||
if (firstStockShortageJob != null && firstStockShortageSaleId != null) {
|
||
await _handleQueuedStockShortage(
|
||
saleId: firstStockShortageSaleId,
|
||
job: firstStockShortageJob,
|
||
shouldPrint: false,
|
||
);
|
||
}
|
||
}
|
||
|
||
for (final job in completed) {
|
||
final requestId = job['request_id']?.toString();
|
||
if (requestId == null || requestId.isEmpty) continue;
|
||
final localSaleExists =
|
||
_activeSaleId == requestId ||
|
||
_sales.any((sale) => sale.id == requestId);
|
||
if (!localSaleExists) continue;
|
||
if (_activeSaleId == requestId) {
|
||
_openBlankSaleAfterSuccessfulSave();
|
||
} else {
|
||
_completeQueuedSale(requestId);
|
||
}
|
||
final invoiceCode = job['invoice_code']?.toString();
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: invoiceCode == null || invoiceCode.isEmpty
|
||
? 'ثبت فروش قبلی تکمیل شد.'
|
||
: 'ثبت فروش قبلی تکمیل شد ($invoiceCode).',
|
||
);
|
||
}
|
||
} catch (_) {
|
||
// Status recovery must not block opening the quick-sales screen.
|
||
}
|
||
}
|
||
|
||
Future<void> _loadCategories() async {
|
||
if (_loadingCategories) return;
|
||
setState(() {
|
||
_loadingCategories = true;
|
||
});
|
||
try {
|
||
final categories = await _categoryService.getCategoriesTree(
|
||
businessId: widget.businessId,
|
||
);
|
||
if (mounted) {
|
||
setState(() {
|
||
_categoryTree = categories
|
||
.map((e) => CategoryNode.fromMap(e))
|
||
.toList();
|
||
_loadingCategories = false;
|
||
});
|
||
}
|
||
} catch (e) {
|
||
debugPrint('Error loading categories: $e');
|
||
if (mounted) {
|
||
setState(() {
|
||
_loadingCategories = false;
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
List<int> _getCategoryIdsForFilter(int? categoryId) {
|
||
if (categoryId == null) return [];
|
||
|
||
// پیدا کردن node مربوط به دسته انتخاب شده
|
||
final node = findCategoryNode(_categoryTree, categoryId);
|
||
if (node == null) return [categoryId];
|
||
|
||
// جمعآوری تمام IDهای زیردستهها
|
||
return getAllCategoryIds(node);
|
||
}
|
||
|
||
Future<void> _loadRecentProducts() async {
|
||
try {
|
||
final prefs = await SharedPreferences.getInstance();
|
||
final key = '${_recentProductsKey}_${widget.businessId}';
|
||
final jsonString = prefs.getString(key);
|
||
if (jsonString != null) {
|
||
final List<dynamic> decoded = jsonDecode(jsonString);
|
||
if (mounted) {
|
||
setState(() {
|
||
_recentProducts = decoded
|
||
.map((e) => Map<String, dynamic>.from(e))
|
||
.take(_maxRecentProducts)
|
||
.toList();
|
||
});
|
||
}
|
||
}
|
||
} catch (e) {
|
||
// خطا در خواندن تاریخچه، ادامه میدهیم
|
||
}
|
||
}
|
||
|
||
Future<void> _saveRecentProduct(Map<String, dynamic> product) async {
|
||
try {
|
||
final productId = _productIntId(product);
|
||
if (productId == null) return;
|
||
|
||
// حذف محصول اگر قبلاً وجود داشته
|
||
_recentProducts.removeWhere(
|
||
(p) => _productIntId(Map<String, dynamic>.from(p)) == productId,
|
||
);
|
||
|
||
// اضافه کردن به ابتدا
|
||
_recentProducts.insert(0, {
|
||
'id': productId,
|
||
'code':
|
||
_quickSalesDisplayProductBusinessCode(product) ??
|
||
product['code']?.toString(),
|
||
'name': product['name']?.toString(),
|
||
'sales_price': _toNum(
|
||
product['base_sales_price'] ?? product['sales_price'],
|
||
),
|
||
'tax_rate': _toNum(product['sales_tax_rate'] ?? product['tax_rate']),
|
||
'track_inventory': product['track_inventory'] ?? false,
|
||
'added_at': DateTime.now().millisecondsSinceEpoch,
|
||
});
|
||
|
||
// محدود کردن به حداکثر تعداد
|
||
if (_recentProducts.length > _maxRecentProducts) {
|
||
_recentProducts = _recentProducts.take(_maxRecentProducts).toList();
|
||
}
|
||
|
||
// ذخیره در SharedPreferences
|
||
final prefs = await SharedPreferences.getInstance();
|
||
final key = '${_recentProductsKey}_${widget.businessId}';
|
||
await prefs.setString(key, jsonEncode(_recentProducts));
|
||
|
||
if (mounted) {
|
||
setState(() {});
|
||
}
|
||
} catch (e) {
|
||
// خطا در ذخیره، ادامه میدهیم
|
||
}
|
||
}
|
||
|
||
void _onMobileTabChanged() {
|
||
if (_mobileTabController.indexIsChanging) return;
|
||
final index = _mobileTabController.index;
|
||
if (_mobileTabIndex == index && _mobileTabsBuilt.contains(index)) return;
|
||
setState(() {
|
||
_mobileTabIndex = index;
|
||
_mobileTabsBuilt.add(index);
|
||
});
|
||
}
|
||
|
||
bool _isProductStockLoading(int? productId) =>
|
||
productId != null && _loadingStockProductIds.contains(productId);
|
||
|
||
@override
|
||
void dispose() {
|
||
_restoreDesktopRailAfterQuit?.call();
|
||
_parkedPersistDebounce?.cancel();
|
||
if (_parkedHydrated && _activeSaleId.isNotEmpty) {
|
||
_captureActiveSaleIntoList();
|
||
unawaited(
|
||
QuickSalesParkedSalesStorage.save(
|
||
widget.businessId,
|
||
widget.authStore.currentUserId ?? 0,
|
||
QuickSalesParkedSalesBundle(
|
||
activeId: _activeSaleId,
|
||
sales: List.of(_sales),
|
||
),
|
||
scope: _parkedStorageScope,
|
||
),
|
||
);
|
||
}
|
||
_searchDebounce?.cancel();
|
||
_globalDiscountDebounce?.cancel();
|
||
_stockBatchTimer?.cancel();
|
||
_removeBarcodeOverlay();
|
||
_mobileTabController.dispose();
|
||
_barcodeController.dispose();
|
||
_documentDescriptionController.removeListener(
|
||
_onParkedSaleDescriptionChanged,
|
||
);
|
||
_documentDescriptionController.dispose();
|
||
_globalDiscountValueController.dispose();
|
||
_barcodeOverlayScrollController.removeListener(_onBarcodeOverlayScroll);
|
||
_barcodeOverlayScrollController.dispose();
|
||
_barcodeFocus.removeListener(_onBarcodeFocusChanged);
|
||
_barcodeFocus.dispose();
|
||
_keyboardListenerFocus.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
void _applyCurrencyMetaFromCache() {
|
||
final id = _defaultCurrencyId;
|
||
var dp = 2;
|
||
var rm = true;
|
||
final cache = _businessCurrenciesCache;
|
||
if (id != null && cache != null) {
|
||
for (final raw in cache) {
|
||
final c = Map<String, dynamic>.from(raw as Map);
|
||
if ((c['id'] as num?)?.toInt() == id) {
|
||
dp = (c['decimal_places'] as num?)?.toInt() ?? 2;
|
||
rm = c['round_monetary_amounts'] != false;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
_invoiceCurrencyDecimalPlaces = dp;
|
||
_invoiceCurrencyRoundMonetary = rm;
|
||
}
|
||
|
||
Future<void> _loadSettings() async {
|
||
setState(() {
|
||
_loading = true;
|
||
});
|
||
try {
|
||
final results = await Future.wait<dynamic>([
|
||
_quickSalesService.getSettings(businessId: widget.businessId),
|
||
_quickSalesService.getAnonymousCustomer(businessId: widget.businessId),
|
||
]);
|
||
final settings = Map<String, dynamic>.from(results[0] as Map);
|
||
final customer = Map<String, dynamic>.from(results[1] as Map);
|
||
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_settings = settings;
|
||
_anonymousCustomer = Customer(
|
||
id: customer['id'] as int,
|
||
name: customer['name'] as String,
|
||
);
|
||
_selectedCustomer = _anonymousCustomer;
|
||
_defaultWarehouseId = settings['default_warehouse_id'];
|
||
_defaultCurrencyId =
|
||
settings['default_currency_id'] ??
|
||
widget.authStore.currentBusiness?.defaultCurrency?.id;
|
||
_defaultPriceListId = settings['default_price_list_id'];
|
||
_selectedCashRegisterId = settings['default_cash_register_id']
|
||
?.toString();
|
||
_autoPrint = settings['auto_print'] ?? false;
|
||
_enableWarehouseDocument =
|
||
settings['enable_warehouse_document'] ?? true;
|
||
_warehouseDocumentType =
|
||
settings['warehouse_document_type'] ?? 'posted';
|
||
_showInventory = settings['show_inventory'] ?? true;
|
||
_enableStockShortageOverride =
|
||
settings['enable_stock_shortage_override'] ?? false;
|
||
_showPurchasePrice =
|
||
(settings['show_purchase_price'] ?? false) &&
|
||
widget.authStore.canViewPurchasePrice();
|
||
_printTemplateId = settings['print_template_id'];
|
||
_printPaperSize = (settings['print_paper_size'] ?? '80mm')?.toString();
|
||
_autoCreatePaymentDocument =
|
||
settings['auto_create_payment_document'] ?? true;
|
||
_settingsDefaultWarehouseId = _defaultWarehouseId;
|
||
_settingsDefaultCashRegisterId = _selectedCashRegisterId;
|
||
_settingsAutoCreatePaymentDocument = _autoCreatePaymentDocument;
|
||
_applyShareDefaultsFromSettings(settings);
|
||
_priceListCache.clear();
|
||
});
|
||
|
||
try {
|
||
await _hydrateParkedSalesIntoFields();
|
||
} catch (_) {
|
||
_activeSaleId = QuickSalesParkedSale.newId();
|
||
_sales.clear();
|
||
_captureActiveSaleIntoList();
|
||
}
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_loading = false;
|
||
_parkedHydrated = true;
|
||
});
|
||
if (!_parkedSalesHydratedCompleter.isCompleted) {
|
||
_parkedSalesHydratedCompleter.complete();
|
||
}
|
||
|
||
unawaited(_refreshCustomerBalance(preserveApply: _applyCustomerBalance));
|
||
|
||
unawaited(_loadShareGatewaysAndDefaults());
|
||
unawaited(_loadBusinessMetadata());
|
||
|
||
if (_showInventory && _cartItems.isNotEmpty) {
|
||
_refreshAllStocks();
|
||
}
|
||
} catch (e) {
|
||
if (!_parkedSalesHydratedCompleter.isCompleted) {
|
||
_parkedSalesHydratedCompleter.complete();
|
||
}
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'خطا در بارگذاری تنظیمات: ${ErrorExtractor.forContext(e, context)}',
|
||
isError: true,
|
||
);
|
||
setState(() {
|
||
_loading = false;
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> _loadBusinessMetadata() async {
|
||
try {
|
||
final results = await Future.wait<dynamic>([
|
||
BusinessApiService.getBusiness(widget.businessId),
|
||
CurrencyService(
|
||
ApiClient(),
|
||
).listBusinessCurrencies(businessId: widget.businessId),
|
||
]);
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_globalDiscountPolicy = InvoiceGlobalDiscountPolicy.fromBusiness(
|
||
results[0],
|
||
);
|
||
_businessCurrenciesCache = List<Map<String, dynamic>>.from(
|
||
results[1] as List,
|
||
);
|
||
_applyCurrencyMetaFromCache();
|
||
});
|
||
} catch (_) {}
|
||
}
|
||
|
||
void _onParkedSaleDescriptionChanged() {
|
||
if (_parkedHydrated) _schedulePersistParkedSales();
|
||
}
|
||
|
||
bool get _hasCustomPayments {
|
||
if (_payments.isEmpty) return false;
|
||
if (_cashFollowsTotal &&
|
||
_payments.length == 1 &&
|
||
_payments.first.type == TransactionType.cashRegister) {
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
bool get _isActiveSaleBlank {
|
||
final isAnon =
|
||
_selectedCustomer == null ||
|
||
(_anonymousCustomer != null &&
|
||
_selectedCustomer!.id == _anonymousCustomer!.id);
|
||
return _cartItems.isEmpty &&
|
||
isAnon &&
|
||
_documentDescriptionController.text.trim().isEmpty &&
|
||
_globalDiscountValueController.text.trim().isEmpty &&
|
||
!_hasCustomPayments;
|
||
}
|
||
|
||
bool get _shouldShowParkedSalesBar => _parkedHydrated && _sales.length > 1;
|
||
|
||
void _schedulePersistParkedSales() {
|
||
_parkedPersistDebounce?.cancel();
|
||
_parkedPersistDebounce = Timer(const Duration(milliseconds: 400), () {
|
||
unawaited(_persistParkedSalesNow());
|
||
});
|
||
}
|
||
|
||
Future<void> _persistParkedSalesNow() async {
|
||
if (!_parkedHydrated || _activeSaleId.isEmpty) return;
|
||
_captureActiveSaleIntoList();
|
||
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() {
|
||
if (_activeSaleId.isEmpty) return;
|
||
final existingIndex = _sales.indexWhere((s) => s.id == _activeSaleId);
|
||
final createdAt = existingIndex >= 0
|
||
? _sales[existingIndex].createdAt
|
||
: DateTime.now();
|
||
final snap = _snapshotActiveSale(createdAt: createdAt);
|
||
if (existingIndex >= 0) {
|
||
_sales[existingIndex] = snap;
|
||
} else {
|
||
_sales.add(snap);
|
||
}
|
||
final anonId = _anonymousCustomer?.id;
|
||
_sales.removeWhere(
|
||
(s) => s.id != _activeSaleId && s.isBlank(anonymousCustomerId: anonId),
|
||
);
|
||
}
|
||
|
||
QuickSalesParkedSale _snapshotActiveSale({DateTime? createdAt}) {
|
||
final now = DateTime.now();
|
||
return QuickSalesParkedSale(
|
||
id: _activeSaleId,
|
||
createdAt: createdAt ?? now,
|
||
updatedAt: now,
|
||
customer: _selectedCustomer,
|
||
cartItems: _cartItems.map(QuickSalesParkedSale.cloneLine).toList(),
|
||
payments: List<InvoiceTransaction>.from(_payments),
|
||
cashFollowsTotal: _cashFollowsTotal,
|
||
applyCustomerBalance: _applyCustomerBalance,
|
||
cashRegisterId: _selectedCashRegisterId,
|
||
warehouseId: _defaultWarehouseId,
|
||
documentDate: _documentDate,
|
||
documentDescription: _documentDescriptionController.text,
|
||
globalDiscountType: _globalDiscountType,
|
||
globalDiscountValue: _globalDiscountValueController.text,
|
||
autoCreatePaymentDocument: _autoCreatePaymentDocument,
|
||
shareOnlinePaymentEnabled: _shareOnlinePaymentEnabled,
|
||
shareGatewayId: _shareGatewayId,
|
||
shareSendSms: _shareSendSms,
|
||
shareSendEmail: _shareSendEmail,
|
||
shareViaNativeShare: _shareViaNativeShare,
|
||
shareExpiryHours: _shareExpiryHours,
|
||
itemCount: _cartItems.length,
|
||
totalAmount: _totalAmount,
|
||
changeResolution: _validChangeResolution,
|
||
);
|
||
}
|
||
|
||
void _applySaleState(QuickSalesParkedSale sale) {
|
||
_activeSaleId = sale.id;
|
||
var customer = sale.customer ?? _anonymousCustomer;
|
||
if (_anonymousCustomer != null &&
|
||
customer != null &&
|
||
customer.id == _anonymousCustomer!.id) {
|
||
customer = _anonymousCustomer;
|
||
}
|
||
_selectedCustomer = customer;
|
||
_cartItems = sale.cartItems.map(QuickSalesParkedSale.cloneLine).toList();
|
||
_payments = List<InvoiceTransaction>.from(sale.payments);
|
||
_changeResolution = sale.changeResolution;
|
||
_cashFollowsTotal = sale.cashFollowsTotal;
|
||
_applyCustomerBalance = sale.applyCustomerBalance;
|
||
_customerBalance = null;
|
||
_customerBalanceStatus = null;
|
||
_customerBalanceError = null;
|
||
_customerBalanceLoading = false;
|
||
_shareRemainingEnabled = false;
|
||
_checkoutDiscountExpanded = false;
|
||
_selectedCashRegisterId =
|
||
sale.cashRegisterId ?? _settingsDefaultCashRegisterId;
|
||
_defaultWarehouseId = sale.warehouseId ?? _settingsDefaultWarehouseId;
|
||
_documentDate = sale.documentDate;
|
||
_documentDescriptionController.text = sale.documentDescription;
|
||
_globalDiscountType = sale.globalDiscountType;
|
||
_globalDiscountValueController.text = sale.globalDiscountValue;
|
||
_autoCreatePaymentDocument = sale.autoCreatePaymentDocument;
|
||
_shareOnlinePaymentEnabled = sale.shareOnlinePaymentEnabled;
|
||
_shareGatewayId = sale.shareGatewayId;
|
||
_shareSendSms = sale.shareSendSms;
|
||
_shareSendEmail = sale.shareSendEmail;
|
||
_shareViaNativeShare = sale.shareViaNativeShare;
|
||
_shareExpiryHours = sale.shareExpiryHours;
|
||
_productStocks.clear();
|
||
_pendingStockProductIds.clear();
|
||
_loadingStockProductIds.clear();
|
||
_syncShareChannelDefaults();
|
||
}
|
||
|
||
void _applyBlankSaleState() {
|
||
_selectedCustomer = _anonymousCustomer;
|
||
_cartItems = [];
|
||
_payments = [];
|
||
_changeResolution = null;
|
||
_cashFollowsTotal = false;
|
||
_applyCustomerBalance = false;
|
||
_customerBalance = null;
|
||
_customerBalanceStatus = null;
|
||
_customerBalanceError = null;
|
||
_customerBalanceLoading = false;
|
||
_shareRemainingEnabled = false;
|
||
_checkoutDiscountExpanded = false;
|
||
_selectedCashRegisterId = _settingsDefaultCashRegisterId;
|
||
_defaultWarehouseId = _settingsDefaultWarehouseId;
|
||
_documentDate = DateTime.now();
|
||
_documentDescriptionController.clear();
|
||
_globalDiscountType = 'percent';
|
||
_globalDiscountValueController.clear();
|
||
_autoCreatePaymentDocument = _settingsAutoCreatePaymentDocument;
|
||
_productStocks.clear();
|
||
_pendingStockProductIds.clear();
|
||
_loadingStockProductIds.clear();
|
||
if (_settings != null) {
|
||
_applyShareDefaultsFromSettings(_settings!);
|
||
} else {
|
||
_syncShareChannelDefaults();
|
||
}
|
||
}
|
||
|
||
Future<void> _hydrateParkedSalesIntoFields() async {
|
||
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();
|
||
_sales.clear();
|
||
_captureActiveSaleIntoList();
|
||
return;
|
||
}
|
||
_sales
|
||
..clear()
|
||
..addAll(bundle.sales);
|
||
_activeSaleId = bundle.activeId;
|
||
final active = _sales.firstWhere((s) => s.id == _activeSaleId);
|
||
_applySaleState(active);
|
||
}
|
||
|
||
void _afterSaleSwitchUi() {
|
||
_removeBarcodeOverlay();
|
||
_barcodeController.clear();
|
||
_lastFailedSearchQuery = null;
|
||
if (_mobileTabController.index != 0) {
|
||
_mobileTabController.animateTo(0);
|
||
}
|
||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||
if (!mounted) return;
|
||
_barcodeFocus.requestFocus();
|
||
});
|
||
if (_showInventory && _cartItems.isNotEmpty) {
|
||
_refreshAllStocks();
|
||
}
|
||
unawaited(_refreshCustomerBalance(preserveApply: _applyCustomerBalance));
|
||
}
|
||
|
||
void _startNewSale() {
|
||
if (_isSaving) return;
|
||
final t = AppLocalizations.of(context);
|
||
if (_isActiveSaleBlank) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: t.quickSalesParkedNewSaleAlreadyEmpty,
|
||
);
|
||
return;
|
||
}
|
||
_captureActiveSaleIntoList();
|
||
if (_sales.length >= _maxParkedSales) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: t.quickSalesParkedMaxReached(_maxParkedSales),
|
||
isError: true,
|
||
);
|
||
return;
|
||
}
|
||
setState(() {
|
||
_activeSaleId = QuickSalesParkedSale.newId();
|
||
_applyBlankSaleState();
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
_afterSaleSwitchUi();
|
||
}
|
||
|
||
void _openBlankSaleAfterSuccessfulSave() {
|
||
final completedSaleId = _activeSaleId;
|
||
final newSaleId = QuickSalesParkedSale.newId();
|
||
setState(() {
|
||
_activeSaleId = newSaleId;
|
||
_applyBlankSaleState();
|
||
_saveAction = _QuickSalesSaveAction.none;
|
||
|
||
final nextBundle =
|
||
QuickSalesParkedSalesBundle(
|
||
activeId: completedSaleId,
|
||
sales: List<QuickSalesParkedSale>.from(_sales),
|
||
).afterCompletedActiveSale(
|
||
blankSale: _snapshotActiveSale(),
|
||
anonymousCustomerId: _anonymousCustomer?.id,
|
||
);
|
||
_sales
|
||
..clear()
|
||
..addAll(nextBundle.sales);
|
||
_activeSaleId = nextBundle.activeId;
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
_afterSaleSwitchUi();
|
||
}
|
||
|
||
void _openBlankSaleAfterQueuedSave(String requestId) {
|
||
_pendingQuickSaleRequestIds.add(requestId);
|
||
_captureActiveSaleIntoList();
|
||
final newSaleId = QuickSalesParkedSale.newId();
|
||
setState(() {
|
||
_activeSaleId = newSaleId;
|
||
_applyBlankSaleState();
|
||
_saveAction = _QuickSalesSaveAction.none;
|
||
_sales.add(_snapshotActiveSale());
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
_afterSaleSwitchUi();
|
||
}
|
||
|
||
void _completeQueuedSale(String requestId) {
|
||
_pendingQuickSaleRequestIds.remove(requestId);
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_sales.removeWhere(
|
||
(sale) => sale.id == requestId && sale.id != _activeSaleId,
|
||
);
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
}
|
||
|
||
String? _markQueuedSaleFailed(String requestId, {bool notify = true}) {
|
||
_pendingQuickSaleRequestIds.remove(requestId);
|
||
if (!mounted) return null;
|
||
final index = _sales.indexWhere((sale) => sale.id == requestId);
|
||
if (index < 0) return null;
|
||
final oldSale = _sales[index];
|
||
final renewedSaleId = QuickSalesParkedSale.newId();
|
||
final renewedSale = QuickSalesParkedSale.fromJson({
|
||
...oldSale.toJson(),
|
||
'id': renewedSaleId,
|
||
'updated_at': DateTime.now().toIso8601String(),
|
||
});
|
||
setState(() {
|
||
_sales[index] = renewedSale;
|
||
if (_activeSaleId == requestId) {
|
||
_activeSaleId = renewedSale.id;
|
||
_applySaleState(renewedSale);
|
||
}
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
if (notify) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'سبد فروش نگه داشته شد؛ پس از اصلاح میتوانید دوباره ثبت کنید.',
|
||
);
|
||
}
|
||
return renewedSaleId;
|
||
}
|
||
|
||
void _selectParkedSale(String id) {
|
||
if (_isSaving || id == _activeSaleId) return;
|
||
if (_pendingQuickSaleRequestIds.contains(id)) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'این سبد هنوز در حال ثبت است؛ پس از پایان پردازش قابل انتخاب میشود.',
|
||
);
|
||
return;
|
||
}
|
||
QuickSalesParkedSale? target;
|
||
for (final sale in _sales) {
|
||
if (sale.id == id) {
|
||
target = sale;
|
||
break;
|
||
}
|
||
}
|
||
if (target == null) return;
|
||
final selected = target;
|
||
setState(() {
|
||
_captureActiveSaleIntoList();
|
||
_applySaleState(selected);
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
_afterSaleSwitchUi();
|
||
}
|
||
|
||
Future<void> _discardParkedSale(String id) async {
|
||
if (_isSaving) return;
|
||
if (id == _activeSaleId) {
|
||
_captureActiveSaleIntoList();
|
||
}
|
||
final index = _sales.indexWhere((s) => s.id == id);
|
||
if (index < 0) return;
|
||
final sale = _sales[index];
|
||
final isBlank = id == _activeSaleId
|
||
? _isActiveSaleBlank
|
||
: sale.isBlank(anonymousCustomerId: _anonymousCustomer?.id);
|
||
if (!isBlank) {
|
||
final t = AppLocalizations.of(context);
|
||
final confirmed = await showDialog<bool>(
|
||
context: context,
|
||
builder: (context) => AlertDialog(
|
||
title: Text(t.quickSalesParkedDiscardTitle),
|
||
content: Text(t.quickSalesParkedDiscardBody),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.of(context).pop(false),
|
||
child: const Text('انصراف'),
|
||
),
|
||
ElevatedButton(
|
||
onPressed: () => Navigator.of(context).pop(true),
|
||
style: ElevatedButton.styleFrom(
|
||
backgroundColor: Theme.of(context).colorScheme.error,
|
||
foregroundColor: Theme.of(context).colorScheme.onError,
|
||
),
|
||
child: Text(t.quickSalesParkedDiscardConfirm),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
if (confirmed != true || !mounted) return;
|
||
}
|
||
|
||
final wasActive = id == _activeSaleId;
|
||
setState(() {
|
||
_sales.removeWhere((s) => s.id == id);
|
||
if (_sales.isEmpty) {
|
||
if (_activeSaleId.isEmpty) {
|
||
_activeSaleId = QuickSalesParkedSale.newId();
|
||
}
|
||
_applyBlankSaleState();
|
||
_captureActiveSaleIntoList();
|
||
} else if (wasActive) {
|
||
final nextIndex = index < _sales.length ? index : _sales.length - 1;
|
||
_applySaleState(_sales[nextIndex]);
|
||
}
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
if (wasActive) _afterSaleSwitchUi();
|
||
}
|
||
|
||
List<QuickSalesParkedSaleChipData> _parkedSaleChipData(AppLocalizations t) {
|
||
return [
|
||
for (var i = 0; i < _sales.length; i++)
|
||
_chipForSale(_sales[i], index: i, t: t),
|
||
];
|
||
}
|
||
|
||
QuickSalesParkedSaleChipData _chipForSale(
|
||
QuickSalesParkedSale sale, {
|
||
required int index,
|
||
required AppLocalizations t,
|
||
}) {
|
||
final isActive = sale.id == _activeSaleId;
|
||
final customer = isActive ? _selectedCustomer : sale.customer;
|
||
final customerName = customer?.name.trim() ?? '';
|
||
final itemCount = isActive ? _cartItems.length : sale.itemCount;
|
||
final total = isActive ? _totalAmount : sale.totalAmount;
|
||
final isAnon =
|
||
customer == null ||
|
||
(_anonymousCustomer != null && customer.id == _anonymousCustomer!.id);
|
||
final isBlank = isActive
|
||
? _isActiveSaleBlank
|
||
: sale.isBlank(anonymousCustomerId: _anonymousCustomer?.id);
|
||
final String title;
|
||
if (!isAnon && customerName.isNotEmpty) {
|
||
title = customerName;
|
||
} else if (itemCount > 0) {
|
||
title = t.quickSalesParkedSaleFallback(index + 1);
|
||
} else if (isAnon) {
|
||
title = isBlank
|
||
? t.quickSalesParkedNewSale
|
||
: t.quickSalesParkedAnonymousCustomer;
|
||
} else {
|
||
title = t.quickSalesParkedSaleFallback(index + 1);
|
||
}
|
||
final subtitle = itemCount <= 0
|
||
? ''
|
||
: t.quickSalesParkedSaleSubtitle(itemCount, _formatNumber(total));
|
||
return QuickSalesParkedSaleChipData(
|
||
id: sale.id,
|
||
title: title,
|
||
subtitle: subtitle,
|
||
isActive: isActive,
|
||
isBlank: isBlank,
|
||
showDiscard: _sales.length > 1 || !isBlank,
|
||
customerInitial: (!isAnon && customerName.isNotEmpty)
|
||
? customerName
|
||
: null,
|
||
);
|
||
}
|
||
|
||
Widget _withParkedSalesBar(Widget child, {required bool compact}) {
|
||
if (!_shouldShowParkedSalesBar) 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)),
|
||
),
|
||
Expanded(child: child),
|
||
],
|
||
);
|
||
}
|
||
|
||
String? get _selectedCustomerPhone {
|
||
final phone = _selectedCustomer?.phone?.trim();
|
||
return (phone != null && phone.isNotEmpty) ? phone : null;
|
||
}
|
||
|
||
String? get _selectedCustomerEmail {
|
||
final email = _selectedCustomer?.email?.trim();
|
||
return (email != null && email.isNotEmpty) ? email : null;
|
||
}
|
||
|
||
void _syncShareChannelDefaults() {
|
||
final hasPhone = _selectedCustomerPhone != null;
|
||
final hasEmail = _selectedCustomerEmail != null;
|
||
if (!hasPhone) _shareSendSms = false;
|
||
if (!hasEmail) _shareSendEmail = false;
|
||
}
|
||
|
||
void _applyShareDefaultsFromSettings(Map<String, dynamic> settings) {
|
||
_shareOnlinePaymentEnabled =
|
||
settings['default_share_online_payment'] ?? true;
|
||
final gatewayRaw = settings['default_share_gateway_id'];
|
||
if (gatewayRaw is int) {
|
||
_shareGatewayId = gatewayRaw;
|
||
} else if (gatewayRaw is num) {
|
||
_shareGatewayId = gatewayRaw.toInt();
|
||
} else {
|
||
_shareGatewayId = int.tryParse('$gatewayRaw');
|
||
}
|
||
_shareExpiryHours =
|
||
(settings['default_share_expiry_hours'] as num?)?.toInt() ?? 168;
|
||
final channels = settings['default_share_channels'];
|
||
if (channels is List) {
|
||
final set = channels.map((e) => e.toString()).toSet();
|
||
_shareSendSms = set.contains('sms');
|
||
_shareSendEmail = set.contains('email');
|
||
_shareViaNativeShare = set.contains('native');
|
||
}
|
||
_syncShareChannelDefaults();
|
||
}
|
||
|
||
Future<void> _loadShareGatewaysAndDefaults() async {
|
||
if (!mounted) return;
|
||
setState(() => _loadingShareGateways = true);
|
||
try {
|
||
final gateways = await _paymentGatewayService.listBusinessGateways(
|
||
widget.businessId,
|
||
);
|
||
if (!mounted) return;
|
||
|
||
final preserveShareChoices = _parkedHydrated;
|
||
|
||
// اگر در تنظیمات فروش سریع درگاه تعریف نشده، از تنظیمات عمومی اشتراک فاکتور استفاده کن
|
||
if (!preserveShareChoices &&
|
||
(_shareGatewayId == null ||
|
||
_settings?['default_share_gateway_id'] == null)) {
|
||
try {
|
||
final shareSettings =
|
||
await BusinessApiService.getInvoiceShareSettings(
|
||
widget.businessId,
|
||
);
|
||
if (_settings?['default_share_gateway_id'] == null) {
|
||
final g = shareSettings['default_online_payment_gateway_id'];
|
||
if (g is int) {
|
||
_shareGatewayId = g;
|
||
} else if (g is num) {
|
||
_shareGatewayId = g.toInt();
|
||
} else if (g != null) {
|
||
_shareGatewayId = int.tryParse(g.toString());
|
||
}
|
||
}
|
||
if (_settings?['default_share_online_payment'] == null &&
|
||
shareSettings['default_online_payment_enabled'] == true) {
|
||
_shareOnlinePaymentEnabled = true;
|
||
}
|
||
} catch (_) {}
|
||
}
|
||
|
||
final gatewayIds = gateways
|
||
.map((e) => (e['id'] as num?)?.toInt())
|
||
.whereType<int>()
|
||
.toSet();
|
||
setState(() {
|
||
_shareGateways = gateways;
|
||
_loadingShareGateways = false;
|
||
if (_shareGatewayId != null && !gatewayIds.contains(_shareGatewayId)) {
|
||
_shareGatewayId = null;
|
||
}
|
||
if (!preserveShareChoices &&
|
||
_shareOnlinePaymentEnabled &&
|
||
_shareGatewayId == null &&
|
||
gateways.length == 1) {
|
||
_shareGatewayId = (gateways.first['id'] as num?)?.toInt();
|
||
}
|
||
if (gateways.isEmpty) _shareOnlinePaymentEnabled = false;
|
||
if (!preserveShareChoices) {
|
||
_syncShareChannelDefaults();
|
||
}
|
||
});
|
||
} catch (_) {
|
||
if (mounted) {
|
||
setState(() {
|
||
_shareGateways = const [];
|
||
_loadingShareGateways = false;
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
void _onAutoCreatePaymentDocumentChanged(bool value) {
|
||
setState(() {
|
||
_autoCreatePaymentDocument = value;
|
||
_shareRemainingEnabled = false;
|
||
_payments = [];
|
||
_changeResolution = null;
|
||
_cashFollowsTotal = false;
|
||
if (!value) {
|
||
_syncShareChannelDefaults();
|
||
}
|
||
});
|
||
}
|
||
|
||
void _onCustomerChanged(Customer? customer) {
|
||
setState(() {
|
||
_selectedCustomer = customer ?? _anonymousCustomer;
|
||
_applyCustomerBalance = false;
|
||
_customerBalance = null;
|
||
_customerBalanceStatus = null;
|
||
_customerBalanceError = null;
|
||
_changeResolution = null;
|
||
_syncShareChannelDefaults();
|
||
});
|
||
unawaited(_refreshCustomerBalance());
|
||
}
|
||
|
||
void _onDocumentDateChanged(DateTime value) {
|
||
setState(() {
|
||
_documentDate = value;
|
||
_applyCustomerBalance = false;
|
||
_changeResolution = null;
|
||
});
|
||
unawaited(_refreshCustomerBalance());
|
||
}
|
||
|
||
Future<void> _refreshCustomerBalance({bool preserveApply = false}) async {
|
||
final customer = _selectedCustomer;
|
||
final currencyId = _defaultCurrencyId;
|
||
final requestGeneration = ++_customerBalanceRequestGeneration;
|
||
if (customer == null || currencyId == null || _isAnonymousSelected) {
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_customerBalance = null;
|
||
_customerBalanceStatus = null;
|
||
_customerBalanceError = null;
|
||
_customerBalanceLoading = false;
|
||
_applyCustomerBalance = false;
|
||
});
|
||
return;
|
||
}
|
||
|
||
final requestedPersonId = customer.id;
|
||
final requestedDate = _documentDate;
|
||
final keepApply = preserveApply && _applyCustomerBalance;
|
||
setState(() {
|
||
_customerBalanceLoading = true;
|
||
_customerBalanceError = null;
|
||
if (!preserveApply) _applyCustomerBalance = false;
|
||
});
|
||
try {
|
||
final result = await _quickSalesService.getCustomerBalance(
|
||
businessId: widget.businessId,
|
||
personId: requestedPersonId,
|
||
currencyId: currencyId,
|
||
asOfDate: requestedDate,
|
||
);
|
||
if (!mounted || requestGeneration != _customerBalanceRequestGeneration) {
|
||
return;
|
||
}
|
||
if (_selectedCustomer?.id != requestedPersonId ||
|
||
_defaultCurrencyId != currencyId ||
|
||
_documentDate.year != requestedDate.year ||
|
||
_documentDate.month != requestedDate.month ||
|
||
_documentDate.day != requestedDate.day) {
|
||
return;
|
||
}
|
||
final balance = (result['balance'] as num?) ?? 0;
|
||
setState(() {
|
||
_customerBalance = balance;
|
||
_customerBalanceStatus =
|
||
result['status']?.toString() ??
|
||
quickSalesCustomerBalanceStatus(balance);
|
||
_customerBalanceLoading = false;
|
||
_customerBalanceError = null;
|
||
_applyCustomerBalance = keepApply && balance.abs() > _paymentEpsilon;
|
||
_changeResolution = null;
|
||
});
|
||
} catch (error) {
|
||
if (!mounted || requestGeneration != _customerBalanceRequestGeneration) {
|
||
return;
|
||
}
|
||
setState(() {
|
||
_customerBalance = null;
|
||
_customerBalanceStatus = null;
|
||
_customerBalanceLoading = false;
|
||
_customerBalanceError = ErrorExtractor.forContext(error, context);
|
||
_applyCustomerBalance = false;
|
||
});
|
||
}
|
||
}
|
||
|
||
num get _paidAmount =>
|
||
_payments.fold<num>(0, (sum, p) => sum + p.settlesAgainstInvoice);
|
||
|
||
num get _paymentTargetAmount => quickSalesPaymentTarget(
|
||
invoiceTotal: _totalAmount,
|
||
customerBalance: _customerBalance ?? 0,
|
||
applyBalance: _applyCustomerBalance,
|
||
);
|
||
|
||
num get _paymentEpsilon {
|
||
if (_invoiceCurrencyDecimalPlaces <= 0) return 0.5;
|
||
var e = 1.0;
|
||
for (var i = 0; i < _invoiceCurrencyDecimalPlaces; i++) {
|
||
e /= 10;
|
||
}
|
||
return e / 2;
|
||
}
|
||
|
||
num get _remainingAmount {
|
||
if (!_autoCreatePaymentDocument) return _paymentTargetAmount;
|
||
final raw = _paymentTargetAmount - _paidAmount;
|
||
if (raw.abs() <= _paymentEpsilon) return 0;
|
||
return raw;
|
||
}
|
||
|
||
bool get _isOverpaid =>
|
||
_autoCreatePaymentDocument &&
|
||
_paidAmount > _paymentTargetAmount + _paymentEpsilon;
|
||
|
||
num get _changeAmount => _isOverpaid ? _paidAmount - _paymentTargetAmount : 0;
|
||
|
||
QuickSalesChangeResolution? get _validChangeResolution {
|
||
final value = _changeResolution;
|
||
if (!_isOverpaid || value == null) return null;
|
||
return value.isValidFor(_changeAmount, _paymentEpsilon) ? value : null;
|
||
}
|
||
|
||
Future<QuickSalesChangeResolution?> _openChangeResolutionDialog() async {
|
||
if (!_isOverpaid) return null;
|
||
final result = await showDialog<QuickSalesChangeResolution>(
|
||
context: context,
|
||
barrierDismissible: false,
|
||
builder: (dialogContext) => QuickSalesChangeResolutionDialog(
|
||
businessId: widget.businessId,
|
||
currencyId: _defaultCurrencyId,
|
||
overpaymentAmount: _changeAmount,
|
||
currencyUnit: _paymentCurrencyUnit,
|
||
decimalPlaces: _invoiceCurrencyDecimalPlaces,
|
||
customerName: _selectedCustomer?.name ?? 'مشتری ناشناس',
|
||
customerId: _selectedCustomer?.id,
|
||
isAnonymousCustomer: _isAnonymousSelected,
|
||
initialValue: _validChangeResolution,
|
||
),
|
||
);
|
||
if (!mounted || result == null) return null;
|
||
setState(() => _changeResolution = result);
|
||
return result;
|
||
}
|
||
|
||
bool get _isAnonymousSelected {
|
||
if (_selectedCustomer == null || _anonymousCustomer == null) {
|
||
return _selectedCustomer == null;
|
||
}
|
||
return _selectedCustomer!.id == _anonymousCustomer!.id;
|
||
}
|
||
|
||
bool get _shouldShareAfterSave {
|
||
if (!_autoCreatePaymentDocument) return true;
|
||
if (_remainingAmount <= 0 || _isOverpaid) return false;
|
||
return _shareRemainingEnabled;
|
||
}
|
||
|
||
String get _paymentCurrencyUnit =>
|
||
currencyUnitLabelForBusinessCurrencyIdOrNull(
|
||
_defaultCurrencyId,
|
||
_businessCurrenciesCache,
|
||
) ??
|
||
'ریال';
|
||
|
||
void _onPaymentsChanged(List<InvoiceTransaction> payments) {
|
||
setState(() {
|
||
_payments = payments;
|
||
_changeResolution = null;
|
||
InvoiceTransaction? cash;
|
||
for (final p in payments) {
|
||
if (p.type == TransactionType.cashRegister) {
|
||
cash = p;
|
||
break;
|
||
}
|
||
}
|
||
if (cash?.cashRegisterId != null && cash!.cashRegisterId!.isNotEmpty) {
|
||
_selectedCashRegisterId = cash.cashRegisterId;
|
||
}
|
||
if (_remainingAmount <= 0) {
|
||
_shareRemainingEnabled = false;
|
||
}
|
||
});
|
||
}
|
||
|
||
List<Map<String, dynamic>> _buildPaymentPayloads() {
|
||
if (!_autoCreatePaymentDocument) return const [];
|
||
final out = <Map<String, dynamic>>[];
|
||
for (final p in _payments) {
|
||
if (p.amount <= 0) continue;
|
||
final map = <String, dynamic>{
|
||
'transaction_type': p.type.value,
|
||
'type': p.type.value,
|
||
'amount': p.amount,
|
||
'transaction_date': p.transactionDate.toIso8601String(),
|
||
};
|
||
switch (p.type) {
|
||
case TransactionType.cashRegister:
|
||
final id = int.tryParse(p.cashRegisterId ?? '');
|
||
if (id != null) map['cash_register_id'] = id;
|
||
if (p.cashRegisterName != null) {
|
||
map['cash_register_name'] = p.cashRegisterName;
|
||
}
|
||
break;
|
||
case TransactionType.bank:
|
||
final id = int.tryParse(p.bankId ?? '');
|
||
if (id != null) map['bank_id'] = id;
|
||
if (p.bankName != null) map['bank_name'] = p.bankName;
|
||
break;
|
||
case TransactionType.check:
|
||
final id = int.tryParse(p.checkId ?? '');
|
||
if (id != null) map['check_id'] = id;
|
||
if (p.checkNumber != null) map['check_number'] = p.checkNumber;
|
||
break;
|
||
case TransactionType.person:
|
||
final id = int.tryParse(p.personId ?? '');
|
||
if (id != null) map['person_id'] = id;
|
||
if (p.personName != null) map['person_name'] = p.personName;
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
out.add(map);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
String? _validatePayments(AppLocalizations t) {
|
||
if (!_autoCreatePaymentDocument) return null;
|
||
for (final p in _payments) {
|
||
if (p.amount <= 0) continue;
|
||
switch (p.type) {
|
||
case TransactionType.cashRegister:
|
||
if (int.tryParse(p.cashRegisterId ?? '') == null) {
|
||
return t.quickSalesPaySelectCashRegister;
|
||
}
|
||
break;
|
||
case TransactionType.bank:
|
||
if (int.tryParse(p.bankId ?? '') == null) {
|
||
return t.quickSalesPaySelectBank;
|
||
}
|
||
break;
|
||
case TransactionType.check:
|
||
if (int.tryParse(p.checkId ?? '') == null) {
|
||
return t.quickSalesPaySelectCheck;
|
||
}
|
||
break;
|
||
case TransactionType.person:
|
||
if (int.tryParse(p.personId ?? '') == null) {
|
||
return t.quickSalesPayNeedDestination;
|
||
}
|
||
break;
|
||
default:
|
||
return t.quickSalesPayNeedDestination;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
Future<Map<String, dynamic>?> _sendInvoiceShareNotification({
|
||
required int personId,
|
||
required String shareLink,
|
||
required String? invoiceCode,
|
||
required num totalAmount,
|
||
required String channel,
|
||
required String customerName,
|
||
required String? customerMobile,
|
||
}) async {
|
||
final api = ApiClient();
|
||
final response = await api.post<Map<String, dynamic>>(
|
||
'/api/v1/business-notifications/businesses/${widget.businessId}/send',
|
||
data: {
|
||
'person_id': personId,
|
||
'event_type': 'invoice_share_link',
|
||
'context': {
|
||
'share_link': shareLink,
|
||
'customer_name': customerName,
|
||
'customer_mobile': customerMobile ?? '',
|
||
'invoice_number': invoiceCode ?? '',
|
||
'invoice_code': invoiceCode ?? '',
|
||
'final_amount': totalAmount.toDouble(),
|
||
},
|
||
'channel': channel,
|
||
if (channel == 'sms' && customerMobile != null)
|
||
'recipient_mobile': customerMobile,
|
||
},
|
||
);
|
||
return response.data;
|
||
}
|
||
|
||
Future<List<String>> _createAndShareAfterSave({
|
||
required int invoiceId,
|
||
required String? invoiceCode,
|
||
required int personId,
|
||
required num totalAmount,
|
||
required _QuickSalesShareSnapshot shareSnapshot,
|
||
}) async {
|
||
final t = AppLocalizations.of(context);
|
||
final notes = <String>[];
|
||
|
||
if (!widget.authStore.canWriteSection('invoices')) {
|
||
notes.add(t.quickSalesShareNoInvoiceEditPermission);
|
||
return notes;
|
||
}
|
||
|
||
if (shareSnapshot.onlinePaymentEnabled) {
|
||
if (!shareSnapshot.hasGateways) {
|
||
notes.add(t.quickSalesShareNoGateway);
|
||
return notes;
|
||
}
|
||
if (shareSnapshot.gatewayId == null) {
|
||
notes.add(t.quickSalesShareGatewayRequired);
|
||
return notes;
|
||
}
|
||
}
|
||
|
||
try {
|
||
final link = await _invoiceService.createInvoiceShareLink(
|
||
businessId: widget.businessId,
|
||
invoiceId: invoiceId,
|
||
expiresInHours: shareSnapshot.expiryHours,
|
||
onlinePaymentEnabled: shareSnapshot.onlinePaymentEnabled,
|
||
onlinePaymentGatewayId: shareSnapshot.onlinePaymentEnabled
|
||
? shareSnapshot.gatewayId
|
||
: null,
|
||
);
|
||
final shortUrl = link['short_url']?.toString();
|
||
if (shortUrl == null || shortUrl.isEmpty) {
|
||
notes.add(t.quickSalesShareLinkFailed);
|
||
return notes;
|
||
}
|
||
notes.add(t.quickSalesShareLinkCreated);
|
||
|
||
final canNotify = widget.authStore.hasBusinessPermission(
|
||
'notifications',
|
||
'send',
|
||
);
|
||
|
||
if (shareSnapshot.sendSms) {
|
||
if (shareSnapshot.customerMobile == null) {
|
||
notes.add(t.quickSalesShareSmsSkippedNoPhone);
|
||
} else if (!canNotify) {
|
||
notes.add(t.quickSalesShareNoNotificationPermission);
|
||
} else {
|
||
try {
|
||
final response = await _sendInvoiceShareNotification(
|
||
personId: personId,
|
||
shareLink: shortUrl,
|
||
invoiceCode: invoiceCode,
|
||
totalAmount: totalAmount,
|
||
channel: 'sms',
|
||
customerName: shareSnapshot.customerName,
|
||
customerMobile: shareSnapshot.customerMobile,
|
||
);
|
||
if (!mounted) return notes;
|
||
final result = response?['data'] as Map<String, dynamic>?;
|
||
final smsResult =
|
||
(result?['results'] as Map<String, dynamic>?)?['sms']
|
||
as Map<String, dynamic>?;
|
||
if (smsResult?['success'] == true) {
|
||
notes.add(t.personShareSmsSent);
|
||
} else {
|
||
final error = smsResult?['error']?.toString() ?? '';
|
||
if (error.contains('قالب') ||
|
||
error.contains('فعال') ||
|
||
error.contains('template')) {
|
||
notes.add(t.quickSalesShareNoTemplateHint);
|
||
} else if (error.isNotEmpty) {
|
||
notes.add(error);
|
||
}
|
||
}
|
||
} catch (e) {
|
||
notes.add(_errorText(e));
|
||
}
|
||
}
|
||
}
|
||
|
||
if (shareSnapshot.sendEmail) {
|
||
if (shareSnapshot.customerEmail == null) {
|
||
notes.add(t.quickSalesShareEmailSkippedNoEmail);
|
||
} else if (!canNotify) {
|
||
notes.add(t.quickSalesShareNoNotificationPermission);
|
||
} else {
|
||
try {
|
||
final response = await _sendInvoiceShareNotification(
|
||
personId: personId,
|
||
shareLink: shortUrl,
|
||
invoiceCode: invoiceCode,
|
||
totalAmount: totalAmount,
|
||
channel: 'email',
|
||
customerName: shareSnapshot.customerName,
|
||
customerMobile: shareSnapshot.customerMobile,
|
||
);
|
||
if (!mounted) return notes;
|
||
final result = response?['data'] as Map<String, dynamic>?;
|
||
final emailResult =
|
||
(result?['results'] as Map<String, dynamic>?)?['email']
|
||
as Map<String, dynamic>?;
|
||
if (emailResult?['success'] == true) {
|
||
notes.add(t.quickSalesShareEmailSent);
|
||
} else {
|
||
final error = emailResult?['error']?.toString() ?? '';
|
||
if (error.contains('قالب') ||
|
||
error.contains('فعال') ||
|
||
error.contains('template')) {
|
||
notes.add(t.quickSalesShareNoTemplateHint);
|
||
} else if (error.isNotEmpty) {
|
||
notes.add(error);
|
||
}
|
||
}
|
||
} catch (e) {
|
||
notes.add(_errorText(e));
|
||
}
|
||
}
|
||
}
|
||
|
||
if (shareSnapshot.useNativeShare) {
|
||
await Share.share(shortUrl);
|
||
}
|
||
|
||
return notes;
|
||
} catch (e) {
|
||
notes.add('${t.quickSalesShareLinkFailed}: ${_errorText(e)}');
|
||
return notes;
|
||
}
|
||
}
|
||
|
||
/// اسکن با `mobile_scanner` فقط اندروید/iOS؛ روی وب از [WebBarcodeScanScreen] استفاده میشود.
|
||
bool get _supportsMobileNativeCameraScan =>
|
||
!kIsWeb &&
|
||
(defaultTargetPlatform == TargetPlatform.android ||
|
||
defaultTargetPlatform == TargetPlatform.iOS);
|
||
|
||
/// نمایش دکمهٔ دوربین: وب (Shape Detection + دوربین) یا موبایل native.
|
||
bool get _supportsCameraScanButton =>
|
||
kIsWeb || _supportsMobileNativeCameraScan;
|
||
|
||
Future<void> _onRecentProductTap(Map<String, dynamic> product) async {
|
||
final productId = _productIntId(product);
|
||
if (productId == null || _recentProductLoadingId != null) return;
|
||
|
||
setState(() => _recentProductLoadingId = productId);
|
||
try {
|
||
final fullProduct = await _productService.getProduct(
|
||
businessId: widget.businessId,
|
||
productId: productId,
|
||
);
|
||
await _addToCart(fullProduct, skipHydrate: true);
|
||
await _saveRecentProduct(fullProduct);
|
||
} catch (e) {
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'خطا در افزودن محصول: ${ErrorExtractor.forContext(e, context)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
} finally {
|
||
if (mounted && _recentProductLoadingId == productId) {
|
||
setState(() => _recentProductLoadingId = null);
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> _scanBarcodeWithCamera() async {
|
||
final String? code;
|
||
if (kIsWeb) {
|
||
code = await Navigator.of(context).push<String>(
|
||
MaterialPageRoute<String>(
|
||
builder: (context) => const WebBarcodeScanScreen(),
|
||
fullscreenDialog: true,
|
||
),
|
||
);
|
||
} else {
|
||
if (!_supportsMobileNativeCameraScan) return;
|
||
code = await Navigator.of(context).push<String>(
|
||
MaterialPageRoute<String>(
|
||
builder: (context) => const MobileBarcodeScanScreen(),
|
||
fullscreenDialog: true,
|
||
),
|
||
);
|
||
}
|
||
if (!mounted || code == null || code.trim().isEmpty) return;
|
||
final trimmed = code.trim();
|
||
_barcodeController.text = trimmed;
|
||
setState(() {});
|
||
await _searchByBarcode(trimmed);
|
||
}
|
||
|
||
Future<void> _searchByBarcode(
|
||
String code, {
|
||
bool showMultipleResultsDialog = true,
|
||
}) async {
|
||
if (code.trim().isEmpty || _barcodeSearching) return;
|
||
|
||
setState(() => _barcodeSearching = true);
|
||
try {
|
||
try {
|
||
// جستجو در کالاهای یونیک
|
||
final instanceData = await _warehouseService.searchInstanceByCode(
|
||
businessId: widget.businessId,
|
||
code: code.trim(),
|
||
);
|
||
|
||
// بررسی اینکه آیا چند نتیجه برگردانده شده یا نه
|
||
final multipleResults = instanceData['multiple_results'] == true;
|
||
final items = instanceData['items'] as List?;
|
||
|
||
if (multipleResults && items != null && items.isNotEmpty) {
|
||
if (!showMultipleResultsDialog) return;
|
||
// اگر چند نتیجه پیدا شد، دیالوگ انتخاب نمایش بده
|
||
if (!mounted) return;
|
||
final selected = await showDialog<Map<String, dynamic>>(
|
||
context: context,
|
||
builder: (context) => _InstanceSelectionDialog(
|
||
instances: items,
|
||
searchCode: code.trim(),
|
||
),
|
||
);
|
||
|
||
if (selected != null) {
|
||
final productId = selected['product_id'] as int?;
|
||
if (productId != null) {
|
||
final product = await _productService.getProduct(
|
||
businessId: widget.businessId,
|
||
productId: productId,
|
||
);
|
||
final instanceId = (selected['id'] as num?)?.toInt();
|
||
final instanceWarehouseId =
|
||
(selected['warehouse_id'] as num?)?.toInt() ??
|
||
(selected['warehouseId'] as num?)?.toInt() ??
|
||
int.tryParse(
|
||
'${selected['warehouse_id'] ?? selected['warehouseId'] ?? ''}',
|
||
);
|
||
await _addToCart(
|
||
product,
|
||
instanceId: instanceId,
|
||
instanceWarehouseId: instanceWarehouseId,
|
||
skipHydrate: true,
|
||
);
|
||
await _saveRecentProduct(product);
|
||
_barcodeController.clear();
|
||
// پاک کردن جستجوی ناموفق قبلی
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
}
|
||
// اگر دیالوگ انتخاب بسته شد بدون انتخاب، جستجوی ناموفق را ثبت کن
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = _canCreateProducts ? code.trim() : null;
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
|
||
// اگر یک نتیجه یا نتیجه مستقیم برگردانده شد
|
||
final productId = instanceData['product_id'] as int?;
|
||
if (productId != null) {
|
||
// دریافت اطلاعات محصول
|
||
final product = await _productService.getProduct(
|
||
businessId: widget.businessId,
|
||
productId: productId,
|
||
);
|
||
|
||
// افزودن به سبد
|
||
final instanceId = (instanceData['id'] as num?)?.toInt();
|
||
final instanceWarehouseId =
|
||
(instanceData['warehouse_id'] as num?)?.toInt() ??
|
||
(instanceData['warehouseId'] as num?)?.toInt() ??
|
||
int.tryParse(
|
||
'${instanceData['warehouse_id'] ?? instanceData['warehouseId'] ?? ''}',
|
||
);
|
||
await _addToCart(
|
||
product,
|
||
instanceId: instanceId,
|
||
instanceWarehouseId: instanceWarehouseId,
|
||
skipHydrate: true,
|
||
);
|
||
await _saveRecentProduct(product);
|
||
_barcodeController.clear();
|
||
// پاک کردن جستجوی ناموفق قبلی
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
} catch (e) {
|
||
// اگر کالای یونیک پیدا نشد، در محصولات عادی جستجو میکنیم
|
||
}
|
||
|
||
// جستجو در محصولات عادی (از طریق کد، بارکد یا نام)
|
||
final categoryIds = _getCategoryIdsForFilter(_selectedCategoryId);
|
||
final products = await _productService.searchProducts(
|
||
businessId: widget.businessId,
|
||
searchQuery: code.trim(),
|
||
limit: 10, // افزایش limit برای بررسی چند نتیجه
|
||
searchFields: const ['code', 'barcode', 'name', 'general_barcodes'],
|
||
categoryIds: categoryIds.isNotEmpty ? categoryIds : null,
|
||
);
|
||
await _hydrateProductMapsBatched(products);
|
||
|
||
if (products.isEmpty) {
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = _canCreateProducts ? code.trim() : null;
|
||
});
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'محصولی یافت نشد',
|
||
isError: true,
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
|
||
// اگر چند نتیجه پیدا شد، دیالوگ انتخاب نمایش بده
|
||
if (products.length > 1) {
|
||
if (!showMultipleResultsDialog) return;
|
||
if (!mounted) return;
|
||
final selected = await showDialog<Map<String, dynamic>>(
|
||
context: context,
|
||
builder: (context) => _ProductSelectionDialog(
|
||
products: products,
|
||
searchCode: code.trim(),
|
||
),
|
||
);
|
||
|
||
if (selected != null) {
|
||
await _addToCart(selected, skipHydrate: true);
|
||
await _saveRecentProduct(selected);
|
||
_barcodeController.clear();
|
||
// پاک کردن جستجوی ناموفق قبلی
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
}
|
||
} else {
|
||
// اگر دیالوگ انتخاب بسته شد بدون انتخاب، جستجوی ناموفق را ثبت کن
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = _canCreateProducts ? code.trim() : null;
|
||
});
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
|
||
// اگر فقط یک نتیجه پیدا شد، مستقیماً اضافه کن
|
||
final product = products.first;
|
||
await _addToCart(product, skipHydrate: true);
|
||
await _saveRecentProduct(product);
|
||
_barcodeController.clear();
|
||
// پاک کردن جستجوی ناموفق قبلی
|
||
if (mounted) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
}
|
||
} catch (e) {
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'خطا در جستجو: ${ErrorExtractor.forContext(e, context)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
} finally {
|
||
if (mounted) {
|
||
setState(() => _barcodeSearching = false);
|
||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||
if (mounted) _barcodeFocus.requestFocus();
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
/// باز کردن دیالوگ افزودن کالا؛ [presetName] در صورت خالی بودن از متن فیلد جستجو استفاده میشود.
|
||
Future<void> _openAddProductDialog({String? presetName}) async {
|
||
if (!_canCreateProducts) {
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'مجوز افزودن کالا و خدمات را ندارید.',
|
||
isError: true,
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
_removeBarcodeOverlay();
|
||
final name = (presetName ?? _barcodeController.text).trim();
|
||
try {
|
||
final result = await showDialog<dynamic>(
|
||
context: context,
|
||
builder: (context) => ProductFormDialog(
|
||
businessId: widget.businessId,
|
||
authStore: widget.authStore,
|
||
product: name.isNotEmpty ? {'name': name} : null,
|
||
onSuccess: () {},
|
||
),
|
||
);
|
||
|
||
if (!mounted) return;
|
||
|
||
// اگر کالا با موفقیت ثبت شد
|
||
if (result != null && result != false) {
|
||
int? newProductId;
|
||
|
||
// استخراج product_id از نتیجه
|
||
if (result is int) {
|
||
newProductId = result;
|
||
} else if (result is Map) {
|
||
newProductId = result['id'] as int?;
|
||
}
|
||
|
||
// اگر product_id را داریم، کالا را دریافت و به سبد اضافه کن
|
||
if (newProductId != null) {
|
||
try {
|
||
final product = await _productService.getProduct(
|
||
businessId: widget.businessId,
|
||
productId: newProductId,
|
||
);
|
||
|
||
await _addToCart(product, skipHydrate: true);
|
||
await _saveRecentProduct(product);
|
||
if (!mounted) return;
|
||
|
||
// پاک کردن جستجوی ناموفق و فیلد جستجو
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
_barcodeController.clear();
|
||
_barcodeFocus.requestFocus();
|
||
} catch (e) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'کالا ثبت شد اما خطا در افزودن به سبد: ${_errorText(e)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
} else {
|
||
// اگر product_id را نداریم، فقط پیام موفقیت نمایش بده
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
_barcodeController.clear();
|
||
_barcodeFocus.requestFocus();
|
||
}
|
||
} else {
|
||
// اگر دیالوگ بسته شد بدون ثبت، جستجوی ناموفق را نگه دار
|
||
// تا کاربر بتواند دوباره روی دکمه + کلیک کند
|
||
}
|
||
} catch (e) {
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'خطا در باز کردن دیالوگ افزودن کالا: ${ErrorExtractor.forContext(e, context)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// تبدیل مقدار به num (پشتیبانی از String و num)
|
||
num _toNum(dynamic value, {num defaultValue = 0.0}) {
|
||
if (value == null) return defaultValue;
|
||
if (value is num) return value;
|
||
if (value is String) {
|
||
return num.tryParse(value) ?? defaultValue;
|
||
}
|
||
return num.tryParse(value.toString()) ?? defaultValue;
|
||
}
|
||
|
||
Future<num?> _getPriceFromPriceList(int productId) async {
|
||
if (_priceListCache.containsKey(productId)) {
|
||
return _priceListCache[productId];
|
||
}
|
||
// اگر لیست قیمت پیشفرض وجود ندارد یا ارز مشخص نشده، null برگردان
|
||
if (_defaultPriceListId == null || _defaultCurrencyId == null) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
final items = await _priceListService.listItems(
|
||
businessId: widget.businessId,
|
||
priceListId: _defaultPriceListId!,
|
||
productId: productId,
|
||
currencyId: _defaultCurrencyId,
|
||
);
|
||
|
||
// جستجوی قیمت برای واحد اصلی (unit_id == null)
|
||
for (final item in items) {
|
||
final unitId = item['unit_id'] as int?;
|
||
final priceValue = item['price'];
|
||
num? price;
|
||
|
||
// تبدیل قیمت به num
|
||
if (priceValue == null) {
|
||
price = null;
|
||
} else if (priceValue is num) {
|
||
price = priceValue;
|
||
} else if (priceValue is String) {
|
||
price = num.tryParse(priceValue);
|
||
} else {
|
||
price = num.tryParse(priceValue.toString());
|
||
}
|
||
|
||
// اگر unit_id null باشد، یعنی قیمت برای واحد اصلی است
|
||
if (unitId == null && price != null && price >= 0) {
|
||
_priceListCache[productId] = price;
|
||
return price;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
// در صورت خطا، null برگردان تا از قیمت پایه استفاده شود
|
||
debugPrint('خطا در دریافت قیمت از لیست قیمت: $e');
|
||
}
|
||
|
||
_priceListCache[productId] = null;
|
||
return null;
|
||
}
|
||
|
||
bool get _hasUniqueItemsInCart =>
|
||
_cartItems.any((it) => it.extraInfo?['instance_id'] != null);
|
||
|
||
/// تغییر انبار انتخابی برای اقلام فاکتور
|
||
/// - مقدار اولیه از تنظیمات (`_defaultWarehouseId`) است
|
||
/// - با تغییر، اقلام سبد همگام میشوند و موجودیها refresh میشوند
|
||
void _onWarehouseForInvoiceChanged(int? newWarehouseId) {
|
||
// اگر کالای یونیک در سبد داریم، برای جلوگیری از چند-انباره شدن فاکتور، تغییر را محدود میکنیم
|
||
if (_hasUniqueItemsInCart && newWarehouseId != null) {
|
||
final conflictingUnique = _cartItems.firstWhere(
|
||
(it) =>
|
||
it.extraInfo?['instance_id'] != null &&
|
||
it.warehouseId != null &&
|
||
it.warehouseId != newWarehouseId,
|
||
orElse: () => InvoiceLineItem(),
|
||
);
|
||
if (conflictingUnique.productId != null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'در سبد کالاهای یونیک از انبار دیگری وجود دارد. ابتدا آن را حذف کنید یا انبار همان کالا را انتخاب کنید.',
|
||
isError: true,
|
||
);
|
||
return;
|
||
}
|
||
}
|
||
|
||
setState(() {
|
||
_defaultWarehouseId = newWarehouseId;
|
||
|
||
// همگامسازی انبار برای اقلام غیر یونیک
|
||
for (var i = 0; i < _cartItems.length; i++) {
|
||
final item = _cartItems[i];
|
||
if (item.extraInfo?['instance_id'] != null) continue; // کالاهای یونیک
|
||
_cartItems[i] = item.copyWith(warehouseId: newWarehouseId);
|
||
}
|
||
|
||
// کش موجودی وابسته به انبار است
|
||
_productStocks.clear();
|
||
_pendingStockProductIds.clear();
|
||
_loadingStockProductIds.clear();
|
||
});
|
||
|
||
// در صورت فعال بودن نمایش موجودی، موجودیها را مجدداً بارگذاری کن
|
||
if (_showInventory) {
|
||
_refreshAllStocks();
|
||
}
|
||
}
|
||
|
||
/// شناسهٔ عددی کالا از map (پشتیبانی از `id` بهصورت رشته با ارقام فارسی).
|
||
int? _productIntId(Map<String, dynamic> p) {
|
||
final v = p['id'];
|
||
if (v is int) return v;
|
||
if (v is num) return v.toInt();
|
||
if (v is String) {
|
||
return int.tryParse(number_utils.toEnglishDigits(v.trim()));
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// اگر نتیجهٔ جستجو [code] را خالی یا برابر [id] برگرداند، با GET تککالا مقدار درست را پر میکنیم.
|
||
bool _shouldHydrateProductCode(Map<String, dynamic> product) {
|
||
final id = _productIntId(product);
|
||
if (id == null) return false;
|
||
final code = number_utils.toEnglishDigits(
|
||
(product['code']?.toString() ?? '').trim(),
|
||
);
|
||
if (code.isEmpty) return true;
|
||
return code == id.toString();
|
||
}
|
||
|
||
Future<void> _hydrateProductCodeIfNeeded(Map<String, dynamic> product) async {
|
||
if (!_shouldHydrateProductCode(product)) return;
|
||
final id = _productIntId(product);
|
||
if (id == null) return;
|
||
try {
|
||
final full = await _productService.getProduct(
|
||
businessId: widget.businessId,
|
||
productId: id,
|
||
);
|
||
if (!mounted || full.isEmpty || _productIntId(full) == null) return;
|
||
for (final k in const [
|
||
'code',
|
||
'product_code',
|
||
'tax_code',
|
||
'name',
|
||
'general_barcodes',
|
||
'barcode',
|
||
'base_sales_price',
|
||
'sales_price',
|
||
'track_inventory',
|
||
'sales_tax_rate',
|
||
'tax_rate',
|
||
'base_purchase_price',
|
||
]) {
|
||
final v = full[k];
|
||
if (v != null && v.toString().trim().isNotEmpty) {
|
||
product[k] = v;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
debugPrint('QuickSales hydrate product code: $e');
|
||
}
|
||
}
|
||
|
||
Future<void> _hydrateProductMapsBatched(
|
||
List<Map<String, dynamic>> items, {
|
||
int batch = 6,
|
||
}) async {
|
||
if (items.isEmpty) return;
|
||
for (var i = 0; i < items.length; i += batch) {
|
||
if (!mounted) return;
|
||
final end = i + batch > items.length ? items.length : i + batch;
|
||
await Future.wait(<Future<void>>[
|
||
for (var j = i; j < end; j++) _hydrateProductCodeIfNeeded(items[j]),
|
||
]);
|
||
}
|
||
}
|
||
|
||
Future<void> _addToCart(
|
||
Map<String, dynamic> product, {
|
||
int? instanceId,
|
||
int? instanceWarehouseId,
|
||
bool skipHydrate = false,
|
||
}) async {
|
||
if (!skipHydrate) {
|
||
await _hydrateProductCodeIfNeeded(product);
|
||
}
|
||
final productId = _productIntId(product);
|
||
if (productId == null) return;
|
||
|
||
setState(() => _addingProductId = productId);
|
||
try {
|
||
final trackInventory = product['track_inventory'] == true;
|
||
|
||
// بررسی اینکه آیا محصول در سبد وجود دارد (فقط برای محصولات غیر یونیک)
|
||
if (instanceId == null) {
|
||
final existingIndex = _cartItems.indexWhere(
|
||
(item) =>
|
||
item.productId == productId &&
|
||
item.extraInfo?['instance_id'] == null,
|
||
);
|
||
|
||
if (existingIndex != -1) {
|
||
// افزایش تعداد محصول موجود
|
||
setState(() {
|
||
final existingItem = _cartItems[existingIndex];
|
||
_cartItems[existingIndex] = existingItem.copyWith(
|
||
quantity: existingItem.quantity + 1,
|
||
);
|
||
});
|
||
// بارگذاری موجودی اگر لازم باشد و نمایش موجودی فعال باشد
|
||
if (trackInventory && _showInventory) {
|
||
_scheduleStockLoads([productId]);
|
||
}
|
||
return;
|
||
}
|
||
}
|
||
|
||
// تلاش برای دریافت قیمت از لیست قیمت
|
||
num unitPrice = 0.0;
|
||
String unitPriceSource = 'base';
|
||
|
||
if (_defaultPriceListId != null && _defaultCurrencyId != null) {
|
||
final priceFromList = await _getPriceFromPriceList(productId);
|
||
if (priceFromList != null) {
|
||
unitPrice = priceFromList;
|
||
unitPriceSource = 'priceList';
|
||
}
|
||
}
|
||
|
||
// صفر یک قیمت معتبر (هدیه/پروموشن) است؛ فقط نبود نتیجه fallback میشود.
|
||
if (unitPriceSource != 'priceList') {
|
||
unitPrice = _toNum(
|
||
product['base_sales_price'] ?? product['sales_price'],
|
||
);
|
||
unitPriceSource = 'base';
|
||
}
|
||
|
||
final lineItem = InvoiceLineItem(
|
||
productId: productId,
|
||
productCode:
|
||
_quickSalesDisplayProductBusinessCode(product) ??
|
||
product['code']?.toString(),
|
||
productName: product['name']?.toString(),
|
||
quantity: instanceId != null ? 1 : 1, // برای کالاهای یونیک همیشه 1
|
||
unitPrice: unitPrice,
|
||
unitPriceSource: unitPriceSource,
|
||
discountType: 'amount',
|
||
discountValue: 0,
|
||
taxRate: _toNum(product['sales_tax_rate'] ?? product['tax_rate']),
|
||
trackInventory: trackInventory,
|
||
warehouseId: instanceWarehouseId ?? _defaultWarehouseId,
|
||
basePurchasePriceMainUnit: product['base_purchase_price'] != null
|
||
? _toNum(product['base_purchase_price'])
|
||
: null,
|
||
extraInfo: instanceId != null
|
||
? {
|
||
'instance_id': instanceId,
|
||
if (instanceWarehouseId != null)
|
||
'instance_warehouse_id': instanceWarehouseId,
|
||
}
|
||
: null,
|
||
);
|
||
|
||
setState(() {
|
||
_cartItems.add(lineItem);
|
||
});
|
||
|
||
// بارگذاری موجودی اگر لازم باشد و نمایش موجودی فعال باشد
|
||
if (trackInventory && instanceId == null && _showInventory) {
|
||
_scheduleStockLoads([productId]);
|
||
}
|
||
} finally {
|
||
if (mounted && _addingProductId == productId) {
|
||
setState(() => _addingProductId = null);
|
||
}
|
||
}
|
||
}
|
||
|
||
void _scheduleStockLoads(Iterable<int> productIds) {
|
||
if (!_showInventory || _defaultWarehouseId == null) return;
|
||
var scheduled = false;
|
||
for (final productId in productIds) {
|
||
if (_productStocks.containsKey(productId) ||
|
||
_loadingStockProductIds.contains(productId)) {
|
||
continue;
|
||
}
|
||
_pendingStockProductIds.add(productId);
|
||
scheduled = true;
|
||
}
|
||
if (!scheduled) return;
|
||
_stockBatchTimer?.cancel();
|
||
_stockBatchTimer = Timer(const Duration(milliseconds: 80), () {
|
||
unawaited(_flushPendingStockLoads());
|
||
});
|
||
}
|
||
|
||
Future<void> _flushPendingStockLoads() async {
|
||
if (!_showInventory ||
|
||
_defaultWarehouseId == null ||
|
||
_pendingStockProductIds.isEmpty) {
|
||
return;
|
||
}
|
||
final productIds = _pendingStockProductIds.toList();
|
||
_pendingStockProductIds.clear();
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_loadingStockProductIds.addAll(productIds);
|
||
});
|
||
try {
|
||
final stockReport = await _warehouseService.getStockReport(
|
||
businessId: widget.businessId,
|
||
query: {
|
||
'product_ids': productIds,
|
||
'warehouse_ids': [_defaultWarehouseId],
|
||
'as_of_date': DateTime.now().toIso8601String().split('T')[0],
|
||
'include_zero': true,
|
||
},
|
||
);
|
||
final items = List<dynamic>.from(stockReport['items'] ?? []);
|
||
final stocksMap = <int, num>{};
|
||
for (final item in items) {
|
||
final pid = (item['product_id'] as num?)?.toInt();
|
||
if (pid != null) {
|
||
stocksMap[pid] = (item['quantity'] as num?) ?? 0;
|
||
}
|
||
}
|
||
if (!mounted) return;
|
||
setState(() {
|
||
for (final productId in productIds) {
|
||
_productStocks[productId] = stocksMap[productId] ?? 0;
|
||
}
|
||
});
|
||
} catch (_) {
|
||
// در صورت خطا، موجودی نمایش داده نمیشود
|
||
} finally {
|
||
if (mounted) {
|
||
setState(() {
|
||
_loadingStockProductIds.removeAll(productIds);
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> _refreshAllStocks() async {
|
||
// اگر نمایش موجودی غیرفعال باشد، موجودی را بهروزرسانی نکن
|
||
if (!_showInventory) {
|
||
return;
|
||
}
|
||
|
||
final trackInventoryProductIds = _cartItems
|
||
.where(
|
||
(item) =>
|
||
item.trackInventory &&
|
||
item.productId != null &&
|
||
item.extraInfo?['instance_id'] == null,
|
||
)
|
||
.map((item) => item.productId!)
|
||
.toSet()
|
||
.toList();
|
||
|
||
if (trackInventoryProductIds.isEmpty || _defaultWarehouseId == null) {
|
||
return;
|
||
}
|
||
|
||
setState(() {
|
||
_loadingStocksBulk = true;
|
||
_loadingStockProductIds.addAll(trackInventoryProductIds);
|
||
});
|
||
|
||
try {
|
||
final stockReport = await _warehouseService.getStockReport(
|
||
businessId: widget.businessId,
|
||
query: {
|
||
'product_ids': trackInventoryProductIds,
|
||
'warehouse_ids': [_defaultWarehouseId],
|
||
'as_of_date': DateTime.now().toIso8601String().split('T')[0],
|
||
'include_zero': true,
|
||
},
|
||
);
|
||
|
||
final items = List<dynamic>.from(stockReport['items'] ?? []);
|
||
final stocksMap = <int, num>{};
|
||
|
||
for (final item in items) {
|
||
final pid = (item['product_id'] as num?)?.toInt();
|
||
if (pid != null) {
|
||
stocksMap[pid] = (item['quantity'] as num?) ?? 0;
|
||
}
|
||
}
|
||
|
||
if (mounted) {
|
||
setState(() {
|
||
_productStocks = stocksMap;
|
||
});
|
||
}
|
||
} catch (e) {
|
||
// در صورت خطا، موجودیهای قبلی باقی میمانند
|
||
} finally {
|
||
if (mounted) {
|
||
setState(() {
|
||
_loadingStocksBulk = false;
|
||
_loadingStockProductIds.removeAll(trackInventoryProductIds);
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
num? _getProductStock(int? productId) {
|
||
if (productId == null) return null;
|
||
return _productStocks[productId];
|
||
}
|
||
|
||
bool _hasInsufficientStock(InvoiceLineItem item) {
|
||
if (!item.trackInventory ||
|
||
item.productId == null ||
|
||
item.extraInfo?['instance_id'] != null) {
|
||
return false; // کالاهای یونیک یا بدون کنترل موجودی
|
||
}
|
||
final stock = _getProductStock(item.productId);
|
||
if (stock == null) return false; // موجودی هنوز لود نشده
|
||
return stock < item.quantity;
|
||
}
|
||
|
||
void _removeFromCart(int index) {
|
||
setState(() {
|
||
final item = _cartItems[index];
|
||
_cartItems.removeAt(index);
|
||
|
||
// اگر آخرین مورد از این محصول حذف شد، موجودی را هم حذف کن
|
||
final hasMoreOfProduct = _cartItems.any(
|
||
(cartItem) =>
|
||
cartItem.productId == item.productId &&
|
||
cartItem.extraInfo?['instance_id'] == null,
|
||
);
|
||
if (!hasMoreOfProduct && item.productId != null) {
|
||
_productStocks.remove(item.productId);
|
||
}
|
||
});
|
||
}
|
||
|
||
Future<void> _clearCart() async {
|
||
if (_cartItems.isEmpty) return;
|
||
|
||
// نمایش دیالوگ تأیید
|
||
final confirmed = await showDialog<bool>(
|
||
context: context,
|
||
builder: (context) => AlertDialog(
|
||
title: const Text('پاک کردن سبد'),
|
||
content: Text(
|
||
'آیا مطمئن هستید که میخواهید همه ${_cartItems.length} محصول را از سبد حذف کنید؟',
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.of(context).pop(false),
|
||
child: const Text('انصراف'),
|
||
),
|
||
ElevatedButton(
|
||
onPressed: () => Navigator.of(context).pop(true),
|
||
style: ElevatedButton.styleFrom(
|
||
backgroundColor: Theme.of(context).colorScheme.error,
|
||
foregroundColor: Theme.of(context).colorScheme.onError,
|
||
),
|
||
child: const Text('پاک کردن'),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
|
||
if (confirmed == true && mounted) {
|
||
setState(() {
|
||
_cartItems.clear();
|
||
_productStocks.clear();
|
||
_globalDiscountValueController.clear();
|
||
});
|
||
_barcodeFocus.requestFocus();
|
||
SnackBarHelper.show(context, message: 'سبد خرید پاک شد');
|
||
}
|
||
}
|
||
|
||
void _updateCartItem(int index, InvoiceLineItem item) {
|
||
setState(() {
|
||
_cartItems[index] = item;
|
||
});
|
||
|
||
// بهروزرسانی موجودی در صورت تغییر تعداد (اگر نمایش موجودی فعال باشد)
|
||
if (item.trackInventory &&
|
||
item.productId != null &&
|
||
item.extraInfo?['instance_id'] == null &&
|
||
_showInventory) {
|
||
_scheduleStockLoads([item.productId!]);
|
||
}
|
||
}
|
||
|
||
num get _lineDiscountOnly =>
|
||
_cartItems.fold<num>(0, (sum, item) => sum + item.discountAmount);
|
||
|
||
num? get _parsedGlobalDiscountValue {
|
||
final raw = _globalDiscountValueController.text.replaceAll(',', '').trim();
|
||
if (raw.isEmpty) return null;
|
||
return num.tryParse(raw);
|
||
}
|
||
|
||
InvoiceGlobalDiscountTotals? get _totalsWithGlobal {
|
||
final gv = _parsedGlobalDiscountValue;
|
||
if (_cartItems.isEmpty || gv == null || gv <= 0) return null;
|
||
return computeInvoiceTotalsWithGlobalDiscount(
|
||
lines: _cartItems,
|
||
globalType: _globalDiscountType,
|
||
globalValue: gv,
|
||
policy: _globalDiscountPolicy,
|
||
decimalPlaces: _invoiceCurrencyDecimalPlaces,
|
||
roundMonetaryAmounts: _invoiceCurrencyRoundMonetary,
|
||
);
|
||
}
|
||
|
||
num get _subtotalAmount {
|
||
return _totalsWithGlobal?.sumSubtotal ??
|
||
_cartItems.fold<num>(0, (sum, item) => sum + item.subtotal);
|
||
}
|
||
|
||
num get _totalDiscount {
|
||
final g = _totalsWithGlobal;
|
||
if (g != null) return g.sumLineDiscount + g.globalDiscountAmount;
|
||
return _lineDiscountOnly;
|
||
}
|
||
|
||
num get _totalTax {
|
||
return _totalsWithGlobal?.sumTax ??
|
||
_cartItems.fold<num>(0, (sum, item) => sum + item.taxAmount);
|
||
}
|
||
|
||
num get _totalAmount {
|
||
return _totalsWithGlobal?.sumTotal ??
|
||
_cartItems.fold<num>(0, (sum, item) => sum + item.total);
|
||
}
|
||
|
||
List<Map<String, dynamic>> _stockShortagesFromError(Object error) {
|
||
if (error is! dio.DioException) return const [];
|
||
final raw = error.response?.data;
|
||
if (raw is! Map) return const [];
|
||
final data = Map<String, dynamic>.from(raw);
|
||
final errorBody = data['error'];
|
||
if (errorBody is! Map || errorBody['code'] != 'INSUFFICIENT_STOCK') {
|
||
return const [];
|
||
}
|
||
final details = errorBody['details'];
|
||
if (details is! Map || details['shortages'] is! List) return const [];
|
||
return (details['shortages'] as List)
|
||
.whereType<Map>()
|
||
.map((e) => Map<String, dynamic>.from(e))
|
||
.toList();
|
||
}
|
||
|
||
Future<_StockShortageAction?> _showStockShortageDialog(
|
||
List<Map<String, dynamic>> 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(
|
||
'اصلاح موجودی این فروش قبلاً ثبت شده است؛ برای جلوگیری از ثبت سند تکراری، اصلاح دوباره در دسترس نیست.',
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
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('اصلاح موجودی'),
|
||
),
|
||
if (canOverride)
|
||
FilledButton(
|
||
onPressed: () =>
|
||
Navigator.pop(dialogContext, _StockShortageAction.override),
|
||
child: const Text('ثبت با موجودی منفی'),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
Future<Map<String, dynamic>?> _askStockOverrideReason() async {
|
||
var reason = 'physical_stock_exists';
|
||
final note = TextEditingController();
|
||
final result = await showDialog<Map<String, dynamic>>(
|
||
context: context,
|
||
builder: (dialogContext) => StatefulBuilder(
|
||
builder: (context, setDialogState) => AlertDialog(
|
||
title: const Text('ثبت یکباره با موجودی منفی'),
|
||
content: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
DropdownButtonFormField<String>(
|
||
value: reason,
|
||
decoration: const InputDecoration(labelText: 'علت'),
|
||
items: const [
|
||
DropdownMenuItem(
|
||
value: 'physical_stock_exists',
|
||
child: Text('کالا بهصورت فیزیکی موجود است'),
|
||
),
|
||
DropdownMenuItem(
|
||
value: 'urgent_sale',
|
||
child: Text('فروش فوری؛ اصلاح بعداً انجام میشود'),
|
||
),
|
||
DropdownMenuItem(value: 'other', child: Text('سایر')),
|
||
],
|
||
onChanged: (value) => setDialogState(
|
||
() => reason = value ?? 'physical_stock_exists',
|
||
),
|
||
),
|
||
const SizedBox(height: 12),
|
||
TextField(
|
||
controller: note,
|
||
decoration: InputDecoration(
|
||
labelText: reason == 'other'
|
||
? 'توضیح (الزامی)'
|
||
: 'توضیح (اختیاری)',
|
||
),
|
||
maxLines: 2,
|
||
),
|
||
],
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.pop(dialogContext),
|
||
child: const Text('انصراف'),
|
||
),
|
||
FilledButton(
|
||
onPressed: () {
|
||
if (reason == 'other' && note.text.trim().isEmpty) return;
|
||
Navigator.pop(dialogContext, {
|
||
'reason_code': reason,
|
||
'reason_note': note.text.trim(),
|
||
'request_token':
|
||
'qs-${widget.businessId}-${DateTime.now().microsecondsSinceEpoch}',
|
||
});
|
||
},
|
||
child: const Text('تأیید و ثبت'),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
note.dispose();
|
||
return result;
|
||
}
|
||
|
||
Future<String?> _correctShortagesBeforeSale(
|
||
List<Map<String, dynamic>> shortages,
|
||
) async {
|
||
final confirmed = await showDialog<bool>(
|
||
context: context,
|
||
builder: (dialogContext) => AlertDialog(
|
||
title: const Text('اصلاح موجودی'),
|
||
content: const Text(
|
||
'این گزینه «کالای درآمدشده» را با همان تاریخ فاکتور ثبت میکند. فقط وقتی ادامه دهید که کالا واقعاً در انبار موجود است و خرید، انتقال یا موجودی اول دورهای از قلم نیفتاده باشد.',
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.pop(dialogContext, false),
|
||
child: const Text('انصراف'),
|
||
),
|
||
FilledButton(
|
||
onPressed: () => Navigator.pop(dialogContext, true),
|
||
child: const Text('تأیید موجودی فیزیکی'),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
if (confirmed != true) return null;
|
||
final documentDate = _documentDate.toIso8601String().split('T').first;
|
||
final requestToken = quickSalesStockCorrectionToken(
|
||
businessId: widget.businessId,
|
||
saleId: _activeSaleId,
|
||
documentDate: _documentDate,
|
||
shortages: shortages,
|
||
);
|
||
await _quickSalesService.createStockCorrection(
|
||
businessId: widget.businessId,
|
||
payload: {
|
||
'document_date': documentDate,
|
||
'request_token': requestToken,
|
||
'confirm_unexplained_physical_surplus': true,
|
||
'description': 'اصلاح کسری کشفشده هنگام فروش سریع',
|
||
'lines': shortages
|
||
.map(
|
||
(s) => {
|
||
'product_id': s['product_id'],
|
||
'warehouse_id': s['warehouse_id'],
|
||
'quantity': s['shortage_quantity'],
|
||
},
|
||
)
|
||
.toList(),
|
||
},
|
||
);
|
||
return requestToken;
|
||
}
|
||
|
||
Future<void> _saveInvoice({
|
||
bool print = false,
|
||
Map<String, dynamic>? stockOverride,
|
||
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;
|
||
}
|
||
|
||
// اعتبارسنجی ارز
|
||
if (_defaultCurrencyId == null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'ارز پیشفرض تنظیم نشده است. لطفاً در تنظیمات فاکتور سریع تنظیم کنید.',
|
||
isError: true,
|
||
);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
|
||
// اگر قرار است حواله انبار صادر شود، انبار الزامی است
|
||
if (_enableWarehouseDocument && _defaultWarehouseId == null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'برای صدور حواله انبار، انتخاب انبار الزامی است',
|
||
isError: true,
|
||
);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
|
||
// اعتبارسنجی پرداخت
|
||
final t = AppLocalizations.of(context);
|
||
if (_autoCreatePaymentDocument) {
|
||
final paymentError = _validatePayments(t);
|
||
if (paymentError != null) {
|
||
SnackBarHelper.show(context, message: paymentError, isError: true);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
}
|
||
if (_autoCreatePaymentDocument &&
|
||
_payments.isEmpty &&
|
||
_paymentTargetAmount > 0 &&
|
||
!debtConfirmed) {
|
||
final confirmed = await showDialog<bool>(
|
||
context: context,
|
||
builder: (dialogContext) => AlertDialog(
|
||
title: const Text('ثبت بدون دریافت'),
|
||
content: Text(
|
||
'هیچ پرداختی ثبت نشده است و مبلغ ${_formatNumber(_paymentTargetAmount)} $_paymentCurrencyUnit در حساب مشتری تسویهنشده میماند. ادامه میدهید؟',
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.pop(dialogContext, false),
|
||
child: const Text('انصراف'),
|
||
),
|
||
FilledButton(
|
||
onPressed: () => Navigator.pop(dialogContext, true),
|
||
child: const Text('ثبت نسیه'),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
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) {
|
||
if (mounted) setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
}
|
||
if (_shouldShareAfterSave) {
|
||
if (_shareOnlinePaymentEnabled) {
|
||
if (_shareGateways.isEmpty) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: t.quickSalesShareNoGateway,
|
||
isError: true,
|
||
);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
if (_shareGatewayId == null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: t.quickSalesShareGatewayRequired,
|
||
isError: true,
|
||
);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
final gv0 = _parsedGlobalDiscountValue;
|
||
if (gv0 != null && gv0 > 0) {
|
||
if (_globalDiscountType == 'percent' && (gv0 < 0 || gv0 > 100)) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: t.invoiceGlobalDiscountPercentInvalid,
|
||
isError: true,
|
||
);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
if (_globalDiscountType == 'amount' && gv0 < 0) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: t.invoiceGlobalDiscountAmountInvalid,
|
||
isError: true,
|
||
);
|
||
setState(() => _saveAction = _QuickSalesSaveAction.none);
|
||
return;
|
||
}
|
||
}
|
||
|
||
final shouldPrint = print || _autoPrint;
|
||
final shouldShare = _shouldShareAfterSave;
|
||
final shareSnapshot = _QuickSalesShareSnapshot(
|
||
onlinePaymentEnabled: _shareOnlinePaymentEnabled,
|
||
hasGateways: _shareGateways.isNotEmpty,
|
||
gatewayId: _shareGatewayId,
|
||
expiryHours: _shareExpiryHours,
|
||
sendSms: _shareSendSms,
|
||
sendEmail: _shareSendEmail,
|
||
useNativeShare: _shareViaNativeShare,
|
||
customerName: _selectedCustomer?.name ?? '',
|
||
customerMobile: _selectedCustomerPhone,
|
||
customerEmail: _selectedCustomerEmail,
|
||
);
|
||
final savedShareAmount = _remainingAmount > 0
|
||
? _remainingAmount
|
||
: _paymentTargetAmount;
|
||
Map<String, dynamic>? retryOverride;
|
||
String? retryCorrectionToken;
|
||
var parkAfterFailure = false;
|
||
|
||
try {
|
||
// ساخت payload
|
||
final lines = _cartItems.map((item) {
|
||
// محاسبه مقادیر
|
||
final lineDiscount = item.discountAmount;
|
||
final taxAmount = item.taxAmount;
|
||
final lineTotal = item.total;
|
||
|
||
// ساختن extra_info با تمام اطلاعات قیمت (مثل new_invoice_page)
|
||
final extraInfoMap = <String, dynamic>{
|
||
'unit_price': item.unitPrice,
|
||
'line_discount': lineDiscount,
|
||
'tax_amount': taxAmount,
|
||
'line_total': lineTotal,
|
||
'unit_price_source': item.unitPriceSource,
|
||
'discount_type': item.discountType,
|
||
'discount_value': item.discountValue,
|
||
'tax_rate': item.taxRate,
|
||
if (item.warehouseId != null) 'warehouse_id': item.warehouseId,
|
||
if (item.extraInfo != null) ...item.extraInfo!,
|
||
};
|
||
|
||
final lineData = <String, dynamic>{
|
||
'product_id': item.productId,
|
||
'quantity': item.quantity,
|
||
'unit_price': item.unitPrice, // برای سازگاری با API قدیمی
|
||
'tax_rate': item.taxRate,
|
||
'discount_type': item.discountType,
|
||
'discount_value': item.discountValue,
|
||
if (item.description != null) 'description': item.description,
|
||
'extra_info': extraInfoMap,
|
||
};
|
||
return lineData;
|
||
}).toList();
|
||
|
||
final payments = _buildPaymentPayloads();
|
||
|
||
// تعیین person_id: اگر مشتری انتخاب شده باشد از آن استفاده میکنیم، وگرنه از مشتری ناشناس
|
||
int? personId;
|
||
if (_selectedCustomer != null &&
|
||
_selectedCustomer != _anonymousCustomer) {
|
||
personId = _selectedCustomer!.id;
|
||
} else if (_anonymousCustomer != null) {
|
||
personId = _anonymousCustomer!.id;
|
||
} else if (_selectedCustomer != null) {
|
||
// fallback: اگر مشتری ناشناس null باشد اما مشتری انتخاب شده باشد
|
||
personId = _selectedCustomer!.id;
|
||
}
|
||
|
||
if (personId == null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'خطا: مشتری ناشناس تنظیم نشده است. لطفاً در تنظیمات فروش سریع یک مشتری پیشفرض انتخاب کنید.',
|
||
isError: true,
|
||
);
|
||
setState(() {
|
||
_saveAction = _QuickSalesSaveAction.none;
|
||
});
|
||
return;
|
||
}
|
||
|
||
// استفاده از سویچ صفحه (پیشفرض از تنظیمات کسبوکار)
|
||
final autoCreatePaymentDoc = _autoCreatePaymentDocument;
|
||
|
||
// ساخت extra_info با person_id و تنظیمات حواله انبار
|
||
final extraInfo = <String, dynamic>{
|
||
'quick_sale': true,
|
||
'quick_sale_request_id': _activeSaleId,
|
||
'person_id': personId, // همیشه person_id را اضافه میکنیم
|
||
'post_inventory': _enableWarehouseDocument, // آیا حواله ایجاد شود؟
|
||
'auto_post_warehouse':
|
||
_enableWarehouseDocument &&
|
||
_warehouseDocumentType == 'posted', // آیا حواله قطعی شود؟
|
||
'auto_create_payment_document': autoCreatePaymentDoc,
|
||
'totals': {
|
||
'gross': _subtotalAmount,
|
||
'discount': _totalDiscount,
|
||
'tax': _totalTax,
|
||
'net': _totalAmount,
|
||
},
|
||
if (_applyCustomerBalance && _customerBalance != null)
|
||
'quick_sale_customer_balance': {
|
||
'apply': true,
|
||
'person_id': personId,
|
||
'currency_id': _defaultCurrencyId,
|
||
'as_of_date': _documentDate.toIso8601String().split('T')[0],
|
||
'balance_before': _customerBalance,
|
||
},
|
||
if (_isOverpaid) 'quick_sale_change': changeResolution!.toJson(),
|
||
};
|
||
|
||
final gvSave = _parsedGlobalDiscountValue;
|
||
if (gvSave != null && gvSave > 0) {
|
||
extraInfo['global_discount'] = {
|
||
'type': _globalDiscountType,
|
||
'value': gvSave.toDouble(),
|
||
};
|
||
}
|
||
|
||
if (_defaultWarehouseId != null) {
|
||
extraInfo['warehouse_id'] = _defaultWarehouseId;
|
||
}
|
||
|
||
final desc = _documentDescriptionController.text.trim();
|
||
final payload = <String, dynamic>{
|
||
'invoice_type': 'invoice_sales',
|
||
'document_date': _documentDate.toIso8601String().split('T')[0],
|
||
'currency_id': _defaultCurrencyId,
|
||
'is_proforma': false,
|
||
'extra_info': extraInfo,
|
||
'lines': lines,
|
||
if (appliedStockCorrectionToken != null)
|
||
'_quick_sale_stock_correction_token': appliedStockCorrectionToken,
|
||
if (payments.isNotEmpty) 'payments': payments,
|
||
if (desc.isNotEmpty) 'description': desc,
|
||
if (stockOverride != null) 'stock_override': stockOverride,
|
||
};
|
||
|
||
final queuedJob = await _invoiceService.enqueueQuickSaleInvoice(
|
||
businessId: widget.businessId,
|
||
payload: payload,
|
||
);
|
||
|
||
if (!mounted) return;
|
||
|
||
final jobStatus = queuedJob['status']?.toString();
|
||
final queuedRequestId =
|
||
queuedJob['request_id']?.toString() ?? _activeSaleId;
|
||
if (jobStatus == 'failed') {
|
||
final errorMessage = queuedJob['error_message']?.toString().trim();
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: errorMessage == null || errorMessage.isEmpty
|
||
? 'ثبت قبلی این فروش ناموفق بود؛ سبد نگه داشته شد و میتوانید دوباره تلاش کنید.'
|
||
: 'ثبت قبلی این فروش ناموفق بود: $errorMessage',
|
||
isError: true,
|
||
);
|
||
_markCurrentSaleRequestForRetry();
|
||
return;
|
||
}
|
||
if (jobStatus != 'completed') {
|
||
_openBlankSaleAfterQueuedSave(queuedRequestId);
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'درخواست فروش برای ثبت ارسال شد؛ میتوانید فروش بعدی را شروع کنید.',
|
||
);
|
||
unawaited(
|
||
_watchQuickSaleInvoiceJob(
|
||
requestId: queuedRequestId,
|
||
personId: personId,
|
||
totalAmount: savedShareAmount,
|
||
shouldPrint: shouldPrint,
|
||
shouldShare: shouldShare,
|
||
shareSnapshot: shareSnapshot,
|
||
),
|
||
);
|
||
return;
|
||
}
|
||
|
||
final result = queuedJob;
|
||
final invoiceId = (result['id'] as num?)?.toInt();
|
||
final invoiceIdFromJob = (result['invoice_id'] as num?)?.toInt();
|
||
final resolvedInvoiceId = invoiceId ?? invoiceIdFromJob;
|
||
final invoiceCode =
|
||
result['code']?.toString() ?? result['invoice_code']?.toString();
|
||
|
||
_openBlankSaleAfterSuccessfulSave();
|
||
|
||
final successMsg = StringBuffer('فاکتور با موفقیت ثبت شد');
|
||
if (invoiceCode != null) successMsg.write(' ($invoiceCode)');
|
||
SnackBarHelper.show(context, message: successMsg.toString());
|
||
|
||
if (resolvedInvoiceId != null && (shouldPrint || shouldShare)) {
|
||
unawaited(
|
||
_runPostSaveTasks(
|
||
invoiceId: resolvedInvoiceId,
|
||
invoiceCode: invoiceCode,
|
||
personId: personId,
|
||
totalAmount: savedShareAmount,
|
||
shouldPrint: shouldPrint,
|
||
shouldShare: shouldShare,
|
||
shareSnapshot: shareSnapshot,
|
||
),
|
||
);
|
||
} else if (shouldPrint && resolvedInvoiceId == null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'فاکتور ثبت شد اما شناسه فاکتور برای چاپ در دسترس نیست',
|
||
isError: true,
|
||
);
|
||
}
|
||
} catch (e) {
|
||
if (mounted) {
|
||
final shortages = _stockShortagesFromError(e);
|
||
if (shortages.isNotEmpty && appliedStockCorrectionToken != null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'اصلاح موجودی ثبت شد، اما فاکتور هنوز به علت کسری موجودی ثبت نشد. تاریخ فاکتور و گردش انبار را بررسی کنید؛ با تکرار ثبت، سند اصلاح جدید ساخته نمیشود.',
|
||
isError: true,
|
||
);
|
||
} else if (shortages.isNotEmpty && stockOverride == null) {
|
||
final action = await _showStockShortageDialog(shortages);
|
||
if (!mounted) return;
|
||
if (action == _StockShortageAction.override) {
|
||
retryOverride = await _askStockOverrideReason();
|
||
if (!mounted) return;
|
||
} else if (action == _StockShortageAction.correct) {
|
||
try {
|
||
retryCorrectionToken = await _correctShortagesBeforeSale(
|
||
shortages,
|
||
);
|
||
} catch (correctionError) {
|
||
if (!mounted) return;
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'اصلاح موجودی انجام نشد: ${ErrorExtractor.forContext(correctionError, context)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
} else if (action == _StockShortageAction.park) {
|
||
parkAfterFailure = true;
|
||
}
|
||
if (action != null && action != _StockShortageAction.cancel) {
|
||
// عملیات انتخابشده پس از آزاد شدن وضعیت ذخیره اجرا میشود.
|
||
} else {
|
||
return;
|
||
}
|
||
} else {
|
||
String errorMessage = 'خطا در ثبت فاکتور';
|
||
if (e.toString().contains('INSUFFICIENT_STOCK')) {
|
||
errorMessage = 'موجودی کافی برای برخی محصولات وجود ندارد';
|
||
} else if (e.toString().contains(
|
||
'QUICK_SALE_CUSTOMER_BALANCE_CHANGED',
|
||
)) {
|
||
errorMessage =
|
||
'مانده حساب مشتری تغییر کرده است؛ مانده جدید را بررسی کنید';
|
||
unawaited(_refreshCustomerBalance());
|
||
} else if (e.toString().contains('CURRENCY')) {
|
||
errorMessage = 'خطا در تنظیمات ارز';
|
||
} else {
|
||
errorMessage =
|
||
'خطا در ثبت فاکتور: ${ErrorExtractor.forContext(e, context)}';
|
||
}
|
||
SnackBarHelper.show(context, message: errorMessage, isError: true);
|
||
}
|
||
}
|
||
} finally {
|
||
if (mounted && _isSaving) {
|
||
setState(() {
|
||
_saveAction = _QuickSalesSaveAction.none;
|
||
});
|
||
}
|
||
}
|
||
if (!mounted) return;
|
||
if (parkAfterFailure) {
|
||
_startNewSale();
|
||
} else if (retryCorrectionToken != null || retryOverride != null) {
|
||
await _saveInvoice(
|
||
print: print,
|
||
stockOverride: retryOverride,
|
||
debtConfirmed: debtConfirmed,
|
||
appliedStockCorrectionToken: retryCorrectionToken,
|
||
);
|
||
}
|
||
}
|
||
|
||
Future<void> _handleQueuedStockShortage({
|
||
required String saleId,
|
||
required Map<String, dynamic> job,
|
||
required bool shouldPrint,
|
||
}) async {
|
||
final shortagesValue = job['error_details'] is Map
|
||
? (job['error_details'] as Map)['shortages']
|
||
: null;
|
||
final shortages = shortagesValue is List
|
||
? shortagesValue
|
||
.whereType<Map>()
|
||
.map((item) => Map<String, dynamic>.from(item))
|
||
.toList()
|
||
: const <Map<String, dynamic>>[];
|
||
if (shortages.isEmpty || !mounted) return;
|
||
|
||
// Keep the next sale intact while bringing the failed basket back for its
|
||
// correction/override workflow. The failed request already has a new ID,
|
||
// so any retry gets a fresh idempotency key.
|
||
_selectParkedSale(saleId);
|
||
final correctionAlreadyApplied =
|
||
(job['error_details'] as Map?)?['stock_correction_already_applied'] ==
|
||
true;
|
||
if (correctionAlreadyApplied) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'اصلاح موجودی قبلی ثبت شده، اما فاکتور هنوز کسری دارد؛ موجودی و تاریخ گردش را بررسی کنید.',
|
||
isError: true,
|
||
);
|
||
}
|
||
final action = await _showStockShortageDialog(
|
||
shortages,
|
||
correctionAlreadyApplied: correctionAlreadyApplied,
|
||
);
|
||
if (!mounted || action == null || action == _StockShortageAction.cancel) {
|
||
return;
|
||
}
|
||
if (action == _StockShortageAction.park) {
|
||
_startNewSale();
|
||
return;
|
||
}
|
||
if (action == _StockShortageAction.override) {
|
||
final override = await _askStockOverrideReason();
|
||
if (!mounted || override == null) return;
|
||
await _saveInvoice(print: shouldPrint, stockOverride: override);
|
||
return;
|
||
}
|
||
|
||
try {
|
||
final correctionToken = await _correctShortagesBeforeSale(shortages);
|
||
if (!mounted || correctionToken == null) return;
|
||
await _saveInvoice(
|
||
print: shouldPrint,
|
||
appliedStockCorrectionToken: correctionToken,
|
||
);
|
||
} catch (error) {
|
||
if (!mounted) return;
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'اصلاح موجودی انجام نشد: ${ErrorExtractor.forContext(error, context)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
}
|
||
|
||
Future<void> _watchQuickSaleInvoiceJob({
|
||
required String requestId,
|
||
required int personId,
|
||
required num totalAmount,
|
||
required bool shouldPrint,
|
||
required bool shouldShare,
|
||
required _QuickSalesShareSnapshot shareSnapshot,
|
||
}) async {
|
||
var pollDelay = const Duration(milliseconds: 500);
|
||
final deadline = DateTime.now().add(const Duration(minutes: 15));
|
||
|
||
while (mounted && DateTime.now().isBefore(deadline)) {
|
||
await Future<void>.delayed(pollDelay);
|
||
if (!mounted) return;
|
||
|
||
Map<String, dynamic> job;
|
||
try {
|
||
job = await _invoiceService.getQuickSaleInvoiceJob(
|
||
businessId: widget.businessId,
|
||
requestId: requestId,
|
||
);
|
||
} catch (_) {
|
||
pollDelay = Duration(
|
||
milliseconds: (pollDelay.inMilliseconds * 1.5)
|
||
.round()
|
||
.clamp(500, 3000)
|
||
.toInt(),
|
||
);
|
||
continue;
|
||
}
|
||
|
||
final status = job['status']?.toString();
|
||
if (status == 'completed') {
|
||
final invoiceId = (job['invoice_id'] as num?)?.toInt();
|
||
final invoiceCode = job['invoice_code']?.toString();
|
||
if (invoiceId == null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: 'ثبت فروش تکمیل شد اما شناسهٔ فاکتور برنگشت.',
|
||
isError: true,
|
||
);
|
||
return;
|
||
}
|
||
_completeQueuedSale(requestId);
|
||
var message = 'فاکتور با موفقیت ثبت شد';
|
||
if (invoiceCode != null && invoiceCode.isNotEmpty) {
|
||
message += ' ($invoiceCode)';
|
||
}
|
||
SnackBarHelper.show(context, message: message);
|
||
if (shouldPrint || shouldShare) {
|
||
unawaited(
|
||
_runPostSaveTasks(
|
||
invoiceId: invoiceId,
|
||
invoiceCode: invoiceCode,
|
||
personId: personId,
|
||
totalAmount: totalAmount,
|
||
shouldPrint: shouldPrint,
|
||
shouldShare: shouldShare,
|
||
shareSnapshot: shareSnapshot,
|
||
),
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (status == 'failed') {
|
||
final errorCode = job['error_code']?.toString();
|
||
final failedSaleId = _markQueuedSaleFailed(requestId, notify: false);
|
||
final errorDetails = job['error_details'];
|
||
final shortageList = errorDetails is Map
|
||
? errorDetails['shortages']
|
||
: null;
|
||
if (errorCode == 'INSUFFICIENT_STOCK' &&
|
||
failedSaleId != null &&
|
||
shortageList is List &&
|
||
shortageList.isNotEmpty) {
|
||
await _handleQueuedStockShortage(
|
||
saleId: failedSaleId,
|
||
job: job,
|
||
shouldPrint: shouldPrint,
|
||
);
|
||
return;
|
||
}
|
||
final message = errorCode == 'INSUFFICIENT_STOCK'
|
||
? 'فروش ثبت نشد؛ موجودی کافی نیست. لطفاً موجودی کالاها را بررسی کنید.'
|
||
: (job['error_message']?.toString().trim().isNotEmpty == true
|
||
? job['error_message'].toString()
|
||
: 'ثبت فروش ناموفق بود. لطفاً دوباره تلاش کنید.');
|
||
SnackBarHelper.show(context, message: message, isError: true);
|
||
if (failedSaleId != null) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'سبد فروش نگه داشته شد؛ پس از اصلاح میتوانید دوباره ثبت کنید.',
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
|
||
pollDelay = Duration(
|
||
milliseconds: (pollDelay.inMilliseconds * 1.5)
|
||
.round()
|
||
.clamp(500, 3000)
|
||
.toInt(),
|
||
);
|
||
}
|
||
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'ثبت فروش هنوز در حال انجام است؛ وضعیت آن در سرور ذخیره شده است.',
|
||
);
|
||
}
|
||
}
|
||
|
||
void _markCurrentSaleRequestForRetry() {
|
||
final oldId = _activeSaleId;
|
||
_captureActiveSaleIntoList();
|
||
final index = _sales.indexWhere((sale) => sale.id == oldId);
|
||
if (index < 0) return;
|
||
final newId = QuickSalesParkedSale.newId();
|
||
final oldSale = _sales[index];
|
||
final renewedSale = QuickSalesParkedSale.fromJson({
|
||
...oldSale.toJson(),
|
||
'id': newId,
|
||
'updated_at': DateTime.now().toIso8601String(),
|
||
});
|
||
setState(() {
|
||
_sales[index] = renewedSale;
|
||
_activeSaleId = newId;
|
||
});
|
||
unawaited(_persistParkedSalesNow());
|
||
}
|
||
|
||
Future<void> _runPostSaveTasks({
|
||
required int invoiceId,
|
||
required String? invoiceCode,
|
||
required int personId,
|
||
required num totalAmount,
|
||
required bool shouldPrint,
|
||
required bool shouldShare,
|
||
required _QuickSalesShareSnapshot shareSnapshot,
|
||
}) async {
|
||
final followUpNotes = <String>[];
|
||
|
||
if (shouldPrint) {
|
||
try {
|
||
await _printInvoice(invoiceId: invoiceId, invoiceCode: invoiceCode);
|
||
} catch (e) {
|
||
followUpNotes.add('خطا در چاپ: ${_errorText(e)}');
|
||
}
|
||
}
|
||
|
||
if (shouldShare) {
|
||
try {
|
||
final shareNotes = await _createAndShareAfterSave(
|
||
invoiceId: invoiceId,
|
||
invoiceCode: invoiceCode,
|
||
personId: personId,
|
||
totalAmount: totalAmount,
|
||
shareSnapshot: shareSnapshot,
|
||
);
|
||
followUpNotes.addAll(shareNotes);
|
||
} catch (e) {
|
||
followUpNotes.add(_errorText(e));
|
||
}
|
||
}
|
||
|
||
if (!mounted || followUpNotes.isEmpty) return;
|
||
SnackBarHelper.show(context, message: followUpNotes.join('\n'));
|
||
}
|
||
|
||
Future<void> _printInvoice({
|
||
required int invoiceId,
|
||
String? invoiceCode,
|
||
}) async {
|
||
try {
|
||
// استفاده از قالب چاپ پیشفرض اگر تنظیم شده باشد
|
||
final query = <String, dynamic>{};
|
||
if (_printTemplateId != null) {
|
||
query['template_id'] = _printTemplateId;
|
||
}
|
||
final paperSize = (_printPaperSize ?? '80mm').trim();
|
||
if (paperSize.isNotEmpty) {
|
||
query['paper_size'] = paperSize;
|
||
}
|
||
query['orientation'] = isInvoiceReceiptPaper(paperSize)
|
||
? 'portrait'
|
||
: 'landscape';
|
||
|
||
final bytes = await _invoiceService.downloadInvoicePdf(
|
||
businessId: widget.businessId,
|
||
invoiceId: invoiceId,
|
||
query: query.isNotEmpty ? query : null,
|
||
);
|
||
|
||
if (!mounted) return;
|
||
|
||
final filename = invoiceCode ?? 'invoice_$invoiceId';
|
||
final safeName = filename.trim().isEmpty ? 'invoice.pdf' : filename;
|
||
final finalName = safeName.toLowerCase().endsWith('.pdf')
|
||
? safeName
|
||
: '$safeName.pdf';
|
||
final result = await BytesExportService.export(
|
||
bytes: bytes,
|
||
filename: finalName,
|
||
mimeType: 'application/pdf',
|
||
);
|
||
if (mounted) BytesExportService.showFeedback(context, result);
|
||
} catch (e) {
|
||
if (mounted) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message:
|
||
'خطا در چاپ فاکتور: ${ErrorExtractor.forContext(e, context)}',
|
||
isError: true,
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> _editCartItem(int index) async {
|
||
final item = _cartItems[index];
|
||
final result = await showDialog<InvoiceLineItem>(
|
||
context: context,
|
||
builder: (context) => _CartItemEditDialog(
|
||
item: item,
|
||
currencyDecimalPlaces: _invoiceCurrencyDecimalPlaces,
|
||
allowEditUnitPrice: widget.authStore.canChangeInvoiceUnitPrice(),
|
||
),
|
||
);
|
||
|
||
if (result != null) {
|
||
_updateCartItem(index, result);
|
||
}
|
||
}
|
||
|
||
void _increaseQuantity(int index) {
|
||
setState(() {
|
||
final item = _cartItems[index];
|
||
|
||
// بررسی موجودی قبل از افزایش
|
||
if (item.trackInventory &&
|
||
item.productId != null &&
|
||
item.extraInfo?['instance_id'] == null) {
|
||
final stock = _getProductStock(item.productId);
|
||
if (stock != null && stock <= item.quantity) {
|
||
SnackBarHelper.show(
|
||
context,
|
||
message: _enableStockShortageOverride
|
||
? 'هشدار کسری موجودی؛ هنگام ثبت درباره نحوه ادامه تصمیم میگیرید. موجودی: ${_formatNumber(stock)}'
|
||
: 'موجودی کافی نیست. موجودی: ${_formatNumber(stock)}',
|
||
isError: true,
|
||
);
|
||
if (!_enableStockShortageOverride) return;
|
||
}
|
||
}
|
||
|
||
_cartItems[index] = item.copyWith(quantity: item.quantity + 1);
|
||
});
|
||
}
|
||
|
||
void _decreaseQuantity(int index) {
|
||
setState(() {
|
||
final item = _cartItems[index];
|
||
if (item.quantity > 1) {
|
||
_cartItems[index] = item.copyWith(quantity: item.quantity - 1);
|
||
}
|
||
});
|
||
}
|
||
|
||
bool _isAnyTextInputFocused() {
|
||
final primary = FocusManager.instance.primaryFocus;
|
||
final ctx = primary?.context;
|
||
if (ctx == null) return false;
|
||
// اگر فوکوس روی هر نوع فیلد متنی/EditableText باشد (یا داخل آن باشد)، نباید میانبرهای سراسری مثل Enter برای ثبت اجرا شوند.
|
||
return ctx.widget is EditableText ||
|
||
ctx.findAncestorWidgetOfExactType<EditableText>() != null;
|
||
}
|
||
|
||
bool get _isDesktopLike =>
|
||
MediaQuery.sizeOf(context).width >=
|
||
ResponsiveHelper.shellPersistentNavMinWidth;
|
||
|
||
void _onBarcodeFocusChanged() {
|
||
if (!mounted || !_isDesktopLike) return;
|
||
if (_barcodeFocus.hasFocus) {
|
||
final query = _barcodeController.text;
|
||
if (shouldShowProductSearchSuggestions(query)) {
|
||
_showBarcodeOverlay();
|
||
_scheduleBarcodeSuggestionSearch(query);
|
||
}
|
||
} else {
|
||
Future.delayed(const Duration(milliseconds: 160), () {
|
||
if (!mounted || _barcodeFocus.hasFocus) return;
|
||
_removeBarcodeOverlay();
|
||
});
|
||
}
|
||
}
|
||
|
||
void _showBarcodeOverlay() {
|
||
if (!mounted || !_isDesktopLike) return;
|
||
if (_barcodeOverlayEntry != null) {
|
||
_barcodeOverlayEntry!.markNeedsBuild();
|
||
return;
|
||
}
|
||
final overlay = Overlay.of(context);
|
||
_barcodeOverlayEntry = OverlayEntry(
|
||
builder: (context) => _buildBarcodeOverlay(context),
|
||
);
|
||
overlay.insert(_barcodeOverlayEntry!);
|
||
}
|
||
|
||
void _removeBarcodeOverlay() {
|
||
_barcodeOverlayEntry?.remove();
|
||
_barcodeOverlayEntry = null;
|
||
_barcodeHighlightedIndex = -1;
|
||
_barcodeSuggestionNavigatedByKeyboard = false;
|
||
}
|
||
|
||
void _clearBarcodeSuggestions({bool removeOverlay = true}) {
|
||
_searchDebounce?.cancel();
|
||
_barcodeSuggestionRequestGeneration++;
|
||
if (mounted) {
|
||
setState(() {
|
||
_barcodeSuggestions = const <Map<String, dynamic>>[];
|
||
_barcodeSuggestionsLoading = false;
|
||
_barcodeSuggestionsLoadingMore = false;
|
||
_barcodeSuggestionsHasMore = false;
|
||
_barcodeSuggestionsSkip = 0;
|
||
_barcodeSuggestionsQuery = '';
|
||
_barcodeHighlightedIndex = -1;
|
||
_barcodeSuggestionNavigatedByKeyboard = false;
|
||
});
|
||
}
|
||
if (removeOverlay) _removeBarcodeOverlay();
|
||
}
|
||
|
||
double _barcodeOverlayHeight() {
|
||
if (_barcodeSuggestionsLoading && _barcodeSuggestions.isEmpty) return 110;
|
||
if (!_barcodeSuggestionsLoading && _barcodeSuggestions.isEmpty) return 90;
|
||
final extra = _barcodeSuggestionsLoadingMore ? 1 : 0;
|
||
final rows = _barcodeSuggestions.length + extra;
|
||
const rowHeight = 56.0;
|
||
final raw = (rows * rowHeight) + (_barcodeSuggestionsLoading ? 4 : 0);
|
||
return raw.clamp(90.0, 320.0);
|
||
}
|
||
|
||
void _onBarcodeOverlayScroll() {
|
||
if (!_barcodeOverlayScrollController.hasClients) return;
|
||
final pos = _barcodeOverlayScrollController.position;
|
||
if (pos.pixels >= pos.maxScrollExtent - 120) {
|
||
_loadMoreBarcodeSuggestions();
|
||
}
|
||
}
|
||
|
||
Widget _buildBarcodeOverlay(BuildContext overlayContext) {
|
||
return Positioned.fill(
|
||
child: CompositedTransformFollower(
|
||
link: _barcodeFieldLayerLink,
|
||
showWhenUnlinked: false,
|
||
targetAnchor: Alignment.bottomLeft,
|
||
followerAnchor: Alignment.topLeft,
|
||
offset: const Offset(0, 6),
|
||
child: Align(
|
||
alignment: Alignment.topLeft,
|
||
child: TextFieldTapRegion(
|
||
child: Material(
|
||
elevation: 10,
|
||
borderRadius: BorderRadius.circular(10),
|
||
clipBehavior: Clip.antiAlias,
|
||
child: ConstrainedBox(
|
||
constraints: const BoxConstraints(maxWidth: 620, minWidth: 300),
|
||
child: SizedBox(
|
||
width: 620,
|
||
height: _barcodeOverlayHeight(),
|
||
child: _buildBarcodeSuggestionList(overlayContext),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildBarcodeSuggestionList(BuildContext context) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
if (_barcodeSuggestionsLoading && _barcodeSuggestions.isEmpty) {
|
||
return const SizedBox(
|
||
height: 110,
|
||
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
|
||
);
|
||
}
|
||
if (!_barcodeSuggestionsLoading && _barcodeSuggestions.isEmpty) {
|
||
return const SizedBox(
|
||
height: 90,
|
||
child: Center(child: Text('کالایی یافت نشد')),
|
||
);
|
||
}
|
||
return Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
if (_barcodeSuggestionsLoading)
|
||
const LinearProgressIndicator(minHeight: 2),
|
||
Flexible(
|
||
child: ListView.separated(
|
||
controller: _barcodeOverlayScrollController,
|
||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||
itemCount:
|
||
_barcodeSuggestions.length +
|
||
(_barcodeSuggestionsLoadingMore ? 1 : 0),
|
||
separatorBuilder: (context, _) =>
|
||
Divider(height: 1, color: cs.outline.withValues(alpha: 0.2)),
|
||
itemBuilder: (context, index) {
|
||
if (_barcodeSuggestionsLoadingMore &&
|
||
index == _barcodeSuggestions.length) {
|
||
return const Padding(
|
||
padding: EdgeInsets.symmetric(vertical: 10),
|
||
child: Center(
|
||
child: SizedBox(
|
||
width: 20,
|
||
height: 20,
|
||
child: CircularProgressIndicator(strokeWidth: 2),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
final product = _barcodeSuggestions[index];
|
||
final selected = index == _barcodeHighlightedIndex;
|
||
final name = product['name']?.toString() ?? 'نامشخص';
|
||
final code = _quickSalesDisplayProductBusinessCode(product) ?? '';
|
||
final gb = productPrimaryBarcodeForSearchDisplay(product);
|
||
final subStyle = TextStyle(
|
||
fontSize: 12,
|
||
color: cs.onSurface.withOpacity(0.72),
|
||
);
|
||
return Material(
|
||
color: selected
|
||
? cs.primary.withValues(alpha: 0.10)
|
||
: Colors.transparent,
|
||
child: ListTile(
|
||
dense: true,
|
||
mouseCursor: SystemMouseCursors.click,
|
||
leading: const Icon(Icons.inventory_2_outlined),
|
||
title: Text(
|
||
name,
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
subtitle: (code.isNotEmpty || gb != null)
|
||
? Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
if (code.isNotEmpty)
|
||
Text('کد: $code', style: subStyle),
|
||
if (gb != null) Text('بارکد: $gb', style: subStyle),
|
||
],
|
||
)
|
||
: null,
|
||
onTap: () => _onBarcodeOverlayRowTapped(product),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
void _scheduleBarcodeSuggestionSearch(String rawQuery) {
|
||
if (!_isDesktopLike) return;
|
||
_searchDebounce?.cancel();
|
||
final query = rawQuery.trim();
|
||
_barcodeSuggestionNavigatedByKeyboard = false;
|
||
if (!shouldShowProductSearchSuggestions(query)) {
|
||
_clearBarcodeSuggestions();
|
||
return;
|
||
}
|
||
_barcodeSuggestionRequestGeneration++;
|
||
if (mounted) {
|
||
setState(() {
|
||
_barcodeSuggestions = const <Map<String, dynamic>>[];
|
||
_barcodeSuggestionsLoading = true;
|
||
_barcodeSuggestionsLoadingMore = false;
|
||
_barcodeSuggestionsHasMore = false;
|
||
_barcodeSuggestionsSkip = 0;
|
||
_barcodeSuggestionsQuery = '';
|
||
_barcodeHighlightedIndex = -1;
|
||
});
|
||
_barcodeOverlayEntry?.markNeedsBuild();
|
||
}
|
||
_searchDebounce = Timer(const Duration(milliseconds: 220), () {
|
||
_loadBarcodeSuggestions(query);
|
||
});
|
||
}
|
||
|
||
Future<void> _loadBarcodeSuggestions(String query) async {
|
||
if (!mounted || !_isDesktopLike) return;
|
||
if (query.isEmpty) {
|
||
_clearBarcodeSuggestions();
|
||
return;
|
||
}
|
||
final requestGeneration = ++_barcodeSuggestionRequestGeneration;
|
||
setState(() {
|
||
_barcodeSuggestionsLoading = true;
|
||
_barcodeSuggestionNavigatedByKeyboard = false;
|
||
});
|
||
_barcodeOverlayEntry?.markNeedsBuild();
|
||
try {
|
||
final categoryIds = _getCategoryIdsForFilter(_selectedCategoryId);
|
||
final products = await _productService.searchProducts(
|
||
businessId: widget.businessId,
|
||
searchQuery: query,
|
||
limit: 20,
|
||
skip: 0,
|
||
searchFields: const ['code', 'barcode', 'name', 'general_barcodes'],
|
||
categoryIds: categoryIds.isNotEmpty ? categoryIds : null,
|
||
);
|
||
await _hydrateProductMapsBatched(products);
|
||
if (!mounted ||
|
||
requestGeneration != _barcodeSuggestionRequestGeneration ||
|
||
_barcodeController.text.trim() != query) {
|
||
return;
|
||
}
|
||
setState(() {
|
||
_barcodeSuggestions = products;
|
||
_barcodeSuggestionsLoadingMore = false;
|
||
_barcodeSuggestionsHasMore = products.length >= 20;
|
||
_barcodeSuggestionsSkip = products.length;
|
||
_barcodeSuggestionsQuery = query;
|
||
_barcodeHighlightedIndex = -1;
|
||
_barcodeSuggestionNavigatedByKeyboard = false;
|
||
});
|
||
_ensureHighlightedSuggestionVisible();
|
||
} catch (_) {
|
||
if (!mounted ||
|
||
requestGeneration != _barcodeSuggestionRequestGeneration) {
|
||
return;
|
||
}
|
||
setState(() {
|
||
_barcodeSuggestions = const <Map<String, dynamic>>[];
|
||
_barcodeSuggestionsLoadingMore = false;
|
||
_barcodeSuggestionsHasMore = false;
|
||
_barcodeSuggestionsSkip = 0;
|
||
_barcodeHighlightedIndex = -1;
|
||
});
|
||
} finally {
|
||
if (mounted && requestGeneration == _barcodeSuggestionRequestGeneration) {
|
||
setState(() => _barcodeSuggestionsLoading = false);
|
||
_barcodeOverlayEntry?.markNeedsBuild();
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> _loadMoreBarcodeSuggestions() async {
|
||
if (!_barcodeSuggestionsHasMore ||
|
||
_barcodeSuggestionsLoadingMore ||
|
||
_barcodeSuggestionsLoading ||
|
||
_barcodeSuggestionsQuery.isEmpty) {
|
||
return;
|
||
}
|
||
final requestGeneration = _barcodeSuggestionRequestGeneration;
|
||
final query = _barcodeSuggestionsQuery;
|
||
setState(() => _barcodeSuggestionsLoadingMore = true);
|
||
_barcodeOverlayEntry?.markNeedsBuild();
|
||
try {
|
||
final categoryIds = _getCategoryIdsForFilter(_selectedCategoryId);
|
||
final products = await _productService.searchProducts(
|
||
businessId: widget.businessId,
|
||
searchQuery: query,
|
||
limit: 20,
|
||
skip: _barcodeSuggestionsSkip,
|
||
searchFields: const ['code', 'barcode', 'name', 'general_barcodes'],
|
||
categoryIds: categoryIds.isNotEmpty ? categoryIds : null,
|
||
);
|
||
await _hydrateProductMapsBatched(products);
|
||
if (!mounted ||
|
||
requestGeneration != _barcodeSuggestionRequestGeneration ||
|
||
_barcodeController.text.trim() != query) {
|
||
return;
|
||
}
|
||
setState(() {
|
||
_barcodeSuggestions = [..._barcodeSuggestions, ...products];
|
||
_barcodeSuggestionsHasMore = products.length >= 20;
|
||
_barcodeSuggestionsSkip = _barcodeSuggestions.length;
|
||
_barcodeSuggestionsLoadingMore = false;
|
||
});
|
||
} catch (_) {
|
||
if (!mounted ||
|
||
requestGeneration != _barcodeSuggestionRequestGeneration) {
|
||
return;
|
||
}
|
||
setState(() => _barcodeSuggestionsLoadingMore = false);
|
||
} finally {
|
||
if (requestGeneration == _barcodeSuggestionRequestGeneration) {
|
||
_barcodeOverlayEntry?.markNeedsBuild();
|
||
}
|
||
}
|
||
}
|
||
|
||
void _moveSuggestionHighlight(int delta) {
|
||
if (_barcodeSuggestions.isEmpty) return;
|
||
_barcodeSuggestionNavigatedByKeyboard = true;
|
||
var idx = _barcodeHighlightedIndex;
|
||
if (idx < 0 || idx >= _barcodeSuggestions.length) {
|
||
idx = delta > 0 ? 0 : _barcodeSuggestions.length - 1;
|
||
} else {
|
||
idx = (idx + delta).clamp(0, _barcodeSuggestions.length - 1);
|
||
}
|
||
if (idx == _barcodeHighlightedIndex) return;
|
||
setState(() => _barcodeHighlightedIndex = idx);
|
||
_barcodeOverlayEntry?.markNeedsBuild();
|
||
_ensureHighlightedSuggestionVisible();
|
||
}
|
||
|
||
void _ensureHighlightedSuggestionVisible() {
|
||
if (_barcodeHighlightedIndex < 0 ||
|
||
!_barcodeOverlayScrollController.hasClients)
|
||
return;
|
||
const itemExtent = 56.0;
|
||
final pos = _barcodeOverlayScrollController.position;
|
||
final target = _barcodeHighlightedIndex * itemExtent;
|
||
final bottom = pos.pixels + pos.viewportDimension - itemExtent;
|
||
if (target < pos.pixels) {
|
||
_barcodeOverlayScrollController.animateTo(
|
||
target,
|
||
duration: const Duration(milliseconds: 100),
|
||
curve: Curves.easeOut,
|
||
);
|
||
} else if (target > bottom) {
|
||
_barcodeOverlayScrollController.animateTo(
|
||
target - pos.viewportDimension + itemExtent,
|
||
duration: const Duration(milliseconds: 100),
|
||
curve: Curves.easeOut,
|
||
);
|
||
}
|
||
}
|
||
|
||
Future<void> _selectHighlightedBarcodeSuggestion() async {
|
||
if (_barcodeSuggestions.isEmpty) return;
|
||
final idx =
|
||
(_barcodeHighlightedIndex >= 0 &&
|
||
_barcodeHighlightedIndex < _barcodeSuggestions.length)
|
||
? _barcodeHighlightedIndex
|
||
: 0;
|
||
await _selectBarcodeSuggestion(_barcodeSuggestions[idx]);
|
||
}
|
||
|
||
void _onBarcodeOverlayRowTapped(Map<String, dynamic> product) {
|
||
final id = _productIntId(product);
|
||
final now = DateTime.now();
|
||
if (id != null &&
|
||
_lastOverlaySuggestionTapProductId == id &&
|
||
_lastOverlaySuggestionTapAt != null &&
|
||
now.difference(_lastOverlaySuggestionTapAt!) <
|
||
const Duration(milliseconds: 400)) {
|
||
return;
|
||
}
|
||
_lastOverlaySuggestionTapProductId = id;
|
||
_lastOverlaySuggestionTapAt = now;
|
||
unawaited(_selectBarcodeSuggestion(product));
|
||
}
|
||
|
||
Future<void> _selectBarcodeSuggestion(Map<String, dynamic> product) async {
|
||
await _addToCart(product, skipHydrate: true);
|
||
await _saveRecentProduct(product);
|
||
if (!mounted) return;
|
||
_barcodeController.clear();
|
||
_clearBarcodeSuggestions();
|
||
_barcodeFocus.requestFocus();
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
}
|
||
|
||
bool _handleKeyEvent(KeyEvent event) {
|
||
if (event is KeyDownEvent) {
|
||
final isControlPressed = HardwareKeyboard.instance.isControlPressed;
|
||
final isMetaPressed = HardwareKeyboard.instance.isMetaPressed;
|
||
|
||
// ناوبری لیست پیشنهادهای جستجو در دسکتاپ
|
||
if (_barcodeFocus.hasFocus && _barcodeOverlayEntry != null) {
|
||
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
|
||
_moveSuggestionHighlight(1);
|
||
return true;
|
||
}
|
||
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
|
||
_moveSuggestionHighlight(-1);
|
||
return true;
|
||
}
|
||
// Enter روی پیشنهادها فقط در onSubmitted فیلد جستجو پردازش میشود؛
|
||
// تکرار اینجا باعث دو بار _addToCart میشد (KeyboardListener همیشه ignored برمیگرداند).
|
||
if (event.logicalKey == LogicalKeyboardKey.escape) {
|
||
if (_barcodeController.text.isNotEmpty ||
|
||
_barcodeSuggestions.isNotEmpty) {
|
||
_removeBarcodeOverlay();
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
|
||
// Enter: ثبت فاکتور
|
||
if (event.logicalKey == LogicalKeyboardKey.enter &&
|
||
!isControlPressed &&
|
||
!isMetaPressed) {
|
||
// وقتی کاربر داخل فیلدهای متنی (خصوصاً فیلد جستجو) است، Enter باید همان رفتار ورودی/جستجو را داشته باشد
|
||
// و نباید به عنوان "ثبت فاکتور" تفسیر شود.
|
||
if (_isAnyTextInputFocused()) {
|
||
return false;
|
||
}
|
||
if (!_isSaving && _cartItems.isNotEmpty) {
|
||
_saveInvoice(print: false);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// Ctrl/Cmd + P: ثبت و چاپ
|
||
if ((isControlPressed || isMetaPressed) &&
|
||
event.logicalKey == LogicalKeyboardKey.keyP) {
|
||
if (!_isSaving && _cartItems.isNotEmpty) {
|
||
_saveInvoice(print: true);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// +: افزایش تعداد آخرین محصول
|
||
if (event.logicalKey == LogicalKeyboardKey.equal ||
|
||
event.logicalKey == LogicalKeyboardKey.numpadAdd) {
|
||
if (_cartItems.isNotEmpty) {
|
||
_increaseQuantity(_cartItems.length - 1);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// -: کاهش تعداد آخرین محصول
|
||
if (event.logicalKey == LogicalKeyboardKey.minus ||
|
||
event.logicalKey == LogicalKeyboardKey.numpadSubtract) {
|
||
if (_cartItems.isNotEmpty) {
|
||
_decreaseQuantity(_cartItems.length - 1);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// Delete: حذف آخرین محصول
|
||
if (event.logicalKey == LogicalKeyboardKey.delete ||
|
||
event.logicalKey == LogicalKeyboardKey.backspace) {
|
||
// فقط وقتی فیلد جستجو خالی است، Backspace/Delete را به حذف آخرین قلم نگاشت میکنیم
|
||
// تا هنگام ویرایش متن، کاربر بتواند به شکل طبیعی کاراکترها را پاک کند.
|
||
if (_cartItems.isNotEmpty &&
|
||
_barcodeFocus.hasFocus &&
|
||
_barcodeController.text.isEmpty) {
|
||
_removeFromCart(_cartItems.length - 1);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
// Ctrl/Cmd + N: فروش جدید (نگه داشتن سبد فعلی)
|
||
if ((isControlPressed || isMetaPressed) &&
|
||
event.logicalKey == LogicalKeyboardKey.keyN) {
|
||
_startNewSale();
|
||
return true;
|
||
}
|
||
|
||
// Ctrl/Cmd + K: پاک کردن همه سبد
|
||
if ((isControlPressed || isMetaPressed) &&
|
||
event.logicalKey == LogicalKeyboardKey.keyK) {
|
||
_clearCart();
|
||
return true;
|
||
}
|
||
|
||
// Escape: پاک کردن فیلد جستجو
|
||
if (event.logicalKey == LogicalKeyboardKey.escape) {
|
||
if (_barcodeFocus.hasFocus && _barcodeController.text.isNotEmpty) {
|
||
_barcodeController.clear();
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
Widget _buildCustomerSelector({bool dense = false}) {
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
CustomerComboboxWidget(
|
||
selectedCustomer: _selectedCustomer,
|
||
onCustomerChanged: _onCustomerChanged,
|
||
businessId: widget.businessId,
|
||
authStore: widget.authStore,
|
||
isRequired: false,
|
||
enableQuickCreateOnSubmit: true,
|
||
dense: dense,
|
||
label: 'مشتری',
|
||
hintText: 'مشتری ناشناس',
|
||
),
|
||
if (!_isAnonymousSelected) ...[
|
||
const SizedBox(height: 6),
|
||
_buildCustomerBalancePanel(),
|
||
],
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildCustomerBalancePanel() {
|
||
final cs = Theme.of(context).colorScheme;
|
||
if (_customerBalanceLoading) {
|
||
return Container(
|
||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
|
||
decoration: BoxDecoration(
|
||
color: cs.surfaceContainerLow,
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
child: const Row(
|
||
children: [
|
||
SizedBox(
|
||
width: 16,
|
||
height: 16,
|
||
child: CircularProgressIndicator(strokeWidth: 2),
|
||
),
|
||
SizedBox(width: 8),
|
||
Expanded(child: Text('در حال دریافت مانده حساب…')),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
if (_customerBalanceError != null) {
|
||
return Container(
|
||
padding: const EdgeInsetsDirectional.only(start: 10),
|
||
decoration: BoxDecoration(
|
||
color: cs.errorContainer,
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Expanded(
|
||
child: Text(
|
||
'مانده حساب دریافت نشد',
|
||
style: TextStyle(color: cs.onErrorContainer),
|
||
),
|
||
),
|
||
IconButton(
|
||
tooltip: 'تلاش دوباره',
|
||
onPressed: () => unawaited(_refreshCustomerBalance()),
|
||
icon: const Icon(Icons.refresh),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
final balance = _customerBalance;
|
||
if (balance == null) return const SizedBox.shrink();
|
||
final isSettled = balance.abs() <= _paymentEpsilon;
|
||
final status =
|
||
_customerBalanceStatus ?? quickSalesCustomerBalanceStatus(balance);
|
||
final statusColor = isSettled
|
||
? cs.onSurfaceVariant
|
||
: balance < 0
|
||
? cs.error
|
||
: Colors.green.shade700;
|
||
final remainingCredit = balance > _totalAmount ? balance - _totalAmount : 0;
|
||
return Container(
|
||
decoration: BoxDecoration(
|
||
color: cs.surfaceContainerLow,
|
||
borderRadius: BorderRadius.circular(8),
|
||
border: Border.all(color: cs.outlineVariant),
|
||
),
|
||
child: SwitchListTile.adaptive(
|
||
dense: true,
|
||
contentPadding: const EdgeInsetsDirectional.only(start: 10, end: 4),
|
||
secondary: Icon(
|
||
balance < 0
|
||
? Icons.account_balance_wallet_outlined
|
||
: Icons.savings_outlined,
|
||
color: statusColor,
|
||
),
|
||
title: Text.rich(
|
||
TextSpan(
|
||
text: 'مانده حساب: ',
|
||
children: [
|
||
TextSpan(
|
||
text: isSettled
|
||
? 'تسویه'
|
||
: '${_formatNumber(balance.abs())} $_paymentCurrencyUnit — $status',
|
||
style: TextStyle(
|
||
color: statusColor,
|
||
fontWeight: FontWeight.w700,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
subtitle: Text(
|
||
_applyCustomerBalance
|
||
? remainingCredit > _paymentEpsilon
|
||
? 'قابل تسویه: ${_formatNumber(_paymentTargetAmount)} $_paymentCurrencyUnit • اعتبار باقیمانده: ${_formatNumber(remainingCredit)}'
|
||
: 'مبلغ قابل تسویه: ${_formatNumber(_paymentTargetAmount)} $_paymentCurrencyUnit'
|
||
: 'اعمال مانده در مبلغ قابل تسویه این فروش',
|
||
),
|
||
value: _applyCustomerBalance,
|
||
onChanged: isSettled || _isSaving
|
||
? null
|
||
: (value) {
|
||
setState(() {
|
||
_applyCustomerBalance = value;
|
||
_changeResolution = null;
|
||
_shareRemainingEnabled = false;
|
||
});
|
||
},
|
||
),
|
||
);
|
||
}
|
||
|
||
/// تاریخ فاکتور (شمسی/میلادی طبق تنظیم کاربر) و شرح سند — چیدمان فشرده
|
||
Widget _buildDocumentDateAndDescription({
|
||
required bool isMobile,
|
||
bool compact = false,
|
||
}) {
|
||
final dateWidget = DateInputField(
|
||
value: _documentDate,
|
||
labelText: 'تاریخ فاکتور',
|
||
hintText: 'انتخاب تاریخ',
|
||
calendarController: widget.calendarController,
|
||
isDense: true,
|
||
contentPadding: const EdgeInsetsDirectional.only(
|
||
start: 12,
|
||
top: 14,
|
||
bottom: 12,
|
||
end: 12,
|
||
),
|
||
onChanged: (d) {
|
||
if (d != null) {
|
||
_onDocumentDateChanged(d);
|
||
}
|
||
},
|
||
);
|
||
|
||
// همان padding و فضای suffixIcon مثل DateInputField(isDense: true) برای یکسان بودن ارتفاع
|
||
final descWidget = FrequentDescriptionTextField(
|
||
businessId: widget.businessId,
|
||
scope: FrequentDescriptionScope.quickSales,
|
||
controller: _documentDescriptionController,
|
||
maxLines: 1,
|
||
maxLength: 1000,
|
||
buildCounter:
|
||
(context, {required currentLength, required isFocused, maxLength}) =>
|
||
null,
|
||
decoration: InputDecoration(
|
||
labelText: 'شرح',
|
||
hintText: 'اختیاری',
|
||
border: const OutlineInputBorder(),
|
||
isDense: true,
|
||
contentPadding: const EdgeInsets.symmetric(
|
||
horizontal: 12,
|
||
vertical: 16,
|
||
),
|
||
suffixIcon: IgnorePointer(
|
||
child: IconButton(
|
||
icon: const Icon(Icons.calendar_today, color: Colors.transparent),
|
||
onPressed: () {},
|
||
),
|
||
),
|
||
),
|
||
);
|
||
|
||
if (isMobile) {
|
||
if (compact) {
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Padding(padding: const EdgeInsets.only(top: 4), child: dateWidget),
|
||
Theme(
|
||
data: Theme.of(
|
||
context,
|
||
).copyWith(dividerColor: Colors.transparent),
|
||
child: ExpansionTile(
|
||
tilePadding: EdgeInsets.zero,
|
||
childrenPadding: const EdgeInsets.only(bottom: 4),
|
||
title: Text(
|
||
'شرح سند (اختیاری)',
|
||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||
),
|
||
),
|
||
initiallyExpanded: true,
|
||
children: [descWidget],
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [dateWidget, const SizedBox(height: 8), descWidget],
|
||
);
|
||
}
|
||
|
||
return Row(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
SizedBox(width: 200, child: dateWidget),
|
||
const SizedBox(width: 12),
|
||
Expanded(child: descWidget),
|
||
],
|
||
);
|
||
}
|
||
|
||
/// ردیف تعداد و جزئیات مالی قلم سبد؛ در حالت compact زیرهم تا از overflow جلوگیری شود.
|
||
Widget _buildCartItemQuantityAndTotals({
|
||
required InvoiceLineItem item,
|
||
required int index,
|
||
required ColorScheme cs,
|
||
required bool compact,
|
||
}) {
|
||
final stepper = Container(
|
||
decoration: BoxDecoration(
|
||
border: Border.all(color: cs.outline),
|
||
borderRadius: BorderRadius.circular(4),
|
||
),
|
||
child: Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
IconButton(
|
||
icon: const Icon(Icons.remove, size: 18),
|
||
onPressed: () => _decreaseQuantity(index),
|
||
padding: const EdgeInsets.all(4),
|
||
constraints: BoxConstraints(
|
||
minWidth: compact ? 28 : 32,
|
||
minHeight: compact ? 28 : 32,
|
||
),
|
||
),
|
||
SizedBox(
|
||
width: compact ? 44 : 50,
|
||
child: Text(
|
||
item.quantity.toStringAsFixed(0),
|
||
textAlign: TextAlign.center,
|
||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||
),
|
||
),
|
||
IconButton(
|
||
icon: const Icon(Icons.add, size: 18),
|
||
onPressed: () => _increaseQuantity(index),
|
||
padding: const EdgeInsets.all(4),
|
||
constraints: BoxConstraints(
|
||
minWidth: compact ? 28 : 32,
|
||
minHeight: compact ? 28 : 32,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
|
||
final breakdown = Column(
|
||
crossAxisAlignment: compact
|
||
? CrossAxisAlignment.start
|
||
: CrossAxisAlignment.end,
|
||
children: [
|
||
Text(
|
||
'${_formatNumber(item.quantity)} × ${_formatNumber(item.unitPrice)}',
|
||
style: TextStyle(
|
||
fontSize: compact ? 11 : 12,
|
||
color: cs.onSurface.withOpacity(0.7),
|
||
),
|
||
),
|
||
if (item.discountValue > 0)
|
||
Text(
|
||
'تخفیف: ${item.discountType == 'percent' ? '${item.discountValue}%' : _formatNumber(item.discountValue)}',
|
||
style: TextStyle(fontSize: compact ? 10 : 11, color: cs.error),
|
||
),
|
||
if (item.taxRate > 0)
|
||
Text(
|
||
'مالیات: ${item.taxRate}%',
|
||
style: TextStyle(
|
||
fontSize: compact ? 10 : 11,
|
||
color: cs.onSurface.withOpacity(0.6),
|
||
),
|
||
),
|
||
],
|
||
);
|
||
|
||
final totalText = Text(
|
||
_formatNumber(item.total),
|
||
style: TextStyle(
|
||
fontWeight: FontWeight.bold,
|
||
fontSize: compact ? 15 : 16,
|
||
color: cs.primary,
|
||
),
|
||
);
|
||
|
||
if (compact) {
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Align(alignment: AlignmentDirectional.centerStart, child: stepper),
|
||
const SizedBox(height: 6),
|
||
Row(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Expanded(child: breakdown),
|
||
const SizedBox(width: 8),
|
||
Flexible(
|
||
child: FittedBox(
|
||
fit: BoxFit.scaleDown,
|
||
alignment: AlignmentDirectional.centerEnd,
|
||
child: totalText,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
return Row(
|
||
children: [
|
||
stepper,
|
||
const SizedBox(width: 16),
|
||
Expanded(child: breakdown),
|
||
const SizedBox(width: 8),
|
||
totalText,
|
||
],
|
||
);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
final screenWidth = MediaQuery.sizeOf(context).width;
|
||
final isMobile = screenWidth < ResponsiveHelper.shellPersistentNavMinWidth;
|
||
final isCompactHeader = screenWidth < _compactBreakpoint;
|
||
|
||
if (_loading) {
|
||
return Scaffold(
|
||
appBar: AppBar(title: const Text('فروش سریع')),
|
||
body: Column(
|
||
children: [
|
||
const LinearProgressIndicator(),
|
||
Expanded(
|
||
child: Center(
|
||
child: Text(
|
||
'در حال بارگذاری تنظیمات فروش سریع...',
|
||
style: TextStyle(color: cs.onSurface.withOpacity(0.7)),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
if (!widget.authStore.canAccessInvoiceType(
|
||
'invoice_sales',
|
||
action: 'add',
|
||
)) {
|
||
return const AccessDeniedPage(
|
||
message: 'دسترسی شما برای فروش سریع محدود شده است',
|
||
);
|
||
}
|
||
|
||
final scaffold = Scaffold(
|
||
appBar: AppBar(
|
||
automaticallyImplyLeading: shouldShowHesabixBackButton(),
|
||
leading: hesabixBackAppBarLeading(
|
||
context,
|
||
businessId: widget.businessId,
|
||
),
|
||
title: isMobile
|
||
? (isCompactHeader
|
||
? Row(
|
||
children: [
|
||
const Expanded(
|
||
child: Text(
|
||
'فروش سریع',
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
),
|
||
if (_cartItems.isNotEmpty)
|
||
Flexible(
|
||
child: Text(
|
||
_formatNumber(_totalAmount),
|
||
style: TextStyle(
|
||
fontSize: 13,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.primary,
|
||
),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
textAlign: TextAlign.end,
|
||
),
|
||
),
|
||
],
|
||
)
|
||
: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
const Text('فروش سریع'),
|
||
if (_cartItems.isNotEmpty)
|
||
Text(
|
||
'${_cartItems.length} قلم • ${_formatNumber(_totalAmount)}',
|
||
style: TextStyle(
|
||
fontSize: 12,
|
||
fontWeight: FontWeight.w600,
|
||
color: cs.primary,
|
||
),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
],
|
||
))
|
||
: Row(
|
||
children: [
|
||
const Text('فروش سریع'),
|
||
if (_cartItems.isNotEmpty) ...[
|
||
const SizedBox(width: 16),
|
||
Container(
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 8,
|
||
vertical: 4,
|
||
),
|
||
decoration: BoxDecoration(
|
||
color: cs.primaryContainer,
|
||
borderRadius: BorderRadius.circular(12),
|
||
),
|
||
child: Text(
|
||
'${_cartItems.length} قلم',
|
||
style: TextStyle(
|
||
fontSize: 12,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onPrimaryContainer,
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(width: 8),
|
||
Text(
|
||
_formatNumber(_totalAmount),
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.primary,
|
||
),
|
||
),
|
||
],
|
||
],
|
||
),
|
||
backgroundColor: cs.surface,
|
||
foregroundColor: cs.onSurface,
|
||
actions: [
|
||
IconButton(
|
||
icon: const Icon(Icons.add),
|
||
tooltip: AppLocalizations.of(
|
||
context,
|
||
).quickSalesParkedNewSaleTooltip,
|
||
onPressed: _isSaving ? null : _startNewSale,
|
||
),
|
||
if (_cartItems.isNotEmpty)
|
||
IconButton(
|
||
icon: const Icon(Icons.clear_all),
|
||
tooltip: 'پاک کردن سبد (Ctrl+K)',
|
||
onPressed: _clearCart,
|
||
),
|
||
IconButton(
|
||
icon: const Icon(Icons.settings),
|
||
tooltip: 'تنظیمات',
|
||
onPressed: () {
|
||
context.push(
|
||
'/business/${widget.businessId}/settings/quick-sales',
|
||
);
|
||
},
|
||
),
|
||
],
|
||
),
|
||
bottomNavigationBar: null,
|
||
body: LayoutBuilder(
|
||
builder: (context, constraints) {
|
||
final isCompact = constraints.maxWidth < _compactBreakpoint;
|
||
if (isMobile) {
|
||
return _withParkedSalesBar(
|
||
_buildMobileTabbedLayout(cs, isCompact: isCompact),
|
||
compact: true,
|
||
);
|
||
}
|
||
final cartColumn = Column(
|
||
children: [
|
||
// جستجوی بارکد
|
||
Container(
|
||
padding: EdgeInsets.all((isMobile && isCompact) ? 12 : 16),
|
||
color: cs.surfaceContainerHighest,
|
||
child: isMobile
|
||
? Column(
|
||
children: [
|
||
Row(
|
||
children: [
|
||
// دکمه refresh موجودی (فقط اگر نمایش موجودی فعال باشد)
|
||
if (_showInventory &&
|
||
_cartItems.any(
|
||
(item) =>
|
||
item.trackInventory &&
|
||
item.productId != null,
|
||
))
|
||
IconButton(
|
||
icon: _loadingStocksBulk
|
||
? const SizedBox(
|
||
width: 20,
|
||
height: 20,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2,
|
||
),
|
||
)
|
||
: const Icon(Icons.refresh),
|
||
onPressed: _loadingStocksBulk
|
||
? null
|
||
: () => _refreshAllStocks(),
|
||
tooltip: 'بهروزرسانی موجودی',
|
||
),
|
||
Expanded(
|
||
child: _buildBarcodeSearchField(
|
||
compact: isCompact,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
SizedBox(height: isCompact ? 6 : 8),
|
||
_buildCustomerSelector(),
|
||
SizedBox(height: isCompact ? 6 : 8),
|
||
_buildDocumentDateAndDescription(
|
||
isMobile: true,
|
||
compact: isCompact,
|
||
),
|
||
],
|
||
)
|
||
: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
// دسکتاپ: فقط جستجوی کالا در ستون اصلی تا ارتفاع بیشتری برای سبد بماند؛
|
||
// مشتری و تاریخ/شرح در ستون کناری (_buildDesktopCheckoutPanel).
|
||
Row(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
if (_showInventory &&
|
||
_cartItems.any(
|
||
(item) =>
|
||
item.trackInventory &&
|
||
item.productId != null,
|
||
))
|
||
IconButton(
|
||
icon: _loadingStocksBulk
|
||
? const SizedBox(
|
||
width: 20,
|
||
height: 20,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2,
|
||
),
|
||
)
|
||
: const Icon(Icons.refresh),
|
||
onPressed: _loadingStocksBulk
|
||
? null
|
||
: () => _refreshAllStocks(),
|
||
tooltip: 'بهروزرسانی موجودی',
|
||
),
|
||
Expanded(
|
||
child: _buildBarcodeSearchField(compact: false),
|
||
),
|
||
],
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// تاریخچه محصولات اخیر
|
||
if (_recentProducts.isNotEmpty && _cartItems.isEmpty)
|
||
Container(
|
||
padding: EdgeInsets.symmetric(
|
||
horizontal: isCompact ? 12 : 16,
|
||
vertical: 8,
|
||
),
|
||
color: cs.surfaceContainerHighest,
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
Icon(
|
||
Icons.history,
|
||
size: 18,
|
||
color: cs.onSurface.withOpacity(0.7),
|
||
),
|
||
const SizedBox(width: 8),
|
||
Text(
|
||
'محصولات اخیر',
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onSurface.withOpacity(0.7),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 8),
|
||
SizedBox(
|
||
height: 60,
|
||
child: ListView.builder(
|
||
scrollDirection: Axis.horizontal,
|
||
itemCount: _recentProducts.length,
|
||
itemBuilder: (context, index) {
|
||
final product = _recentProducts[index];
|
||
return Padding(
|
||
padding: const EdgeInsets.only(right: 8),
|
||
child: InkWell(
|
||
onTap: () => _onRecentProductTap(product),
|
||
child: AnimatedContainer(
|
||
duration: const Duration(milliseconds: 200),
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 12,
|
||
vertical: 8,
|
||
),
|
||
decoration: BoxDecoration(
|
||
color: cs.surface,
|
||
borderRadius: BorderRadius.circular(8),
|
||
border: Border.all(
|
||
color:
|
||
_recentProductLoadingId ==
|
||
_productIntId(product)
|
||
? cs.primary
|
||
: cs.outline.withOpacity(0.3),
|
||
),
|
||
),
|
||
child:
|
||
_recentProductLoadingId ==
|
||
_productIntId(product)
|
||
? SizedBox(
|
||
width: 80,
|
||
child: Center(
|
||
child: SizedBox(
|
||
width: 18,
|
||
height: 18,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2,
|
||
color: cs.primary,
|
||
),
|
||
),
|
||
),
|
||
)
|
||
: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment:
|
||
CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
product['name']?.toString() ??
|
||
'نامشخص',
|
||
style: const TextStyle(
|
||
fontSize: 12,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
'${_formatNumber(_toNum(product['base_sales_price'] ?? product['sales_price']))}',
|
||
style: TextStyle(
|
||
fontSize: 11,
|
||
color: cs.primary,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// لیست سبد خرید
|
||
Expanded(
|
||
child: _cartItems.isEmpty
|
||
? Center(
|
||
child: AnimatedSwitcher(
|
||
duration: const Duration(milliseconds: 300),
|
||
child: Column(
|
||
key: ValueKey(_recentProducts.isEmpty),
|
||
mainAxisAlignment: MainAxisAlignment.center,
|
||
children: [
|
||
Icon(
|
||
Icons.shopping_cart_outlined,
|
||
size: 64,
|
||
color: cs.outline,
|
||
),
|
||
const SizedBox(height: 16),
|
||
Text(
|
||
'سبد خرید خالی است',
|
||
style: TextStyle(color: cs.outline),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
)
|
||
: ListView.builder(
|
||
padding: EdgeInsets.all(isCompact ? 6 : 8),
|
||
itemCount: _cartItems.length,
|
||
itemBuilder: (context, index) {
|
||
final item = _cartItems[index];
|
||
final hasInsufficientStock = _hasInsufficientStock(
|
||
item,
|
||
);
|
||
return AnimatedContainer(
|
||
duration: const Duration(milliseconds: 300),
|
||
curve: Curves.easeInOut,
|
||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||
child: Card(
|
||
color: hasInsufficientStock
|
||
? cs.errorContainer.withOpacity(0.3)
|
||
: null,
|
||
child: InkWell(
|
||
onTap: () => _editCartItem(index),
|
||
child: Padding(
|
||
padding: EdgeInsets.all(isCompact ? 6 : 8),
|
||
child: Column(
|
||
crossAxisAlignment:
|
||
CrossAxisAlignment.start,
|
||
children: [
|
||
// هشدار موجودی ناکافی (فقط اگر نمایش موجودی فعال باشد)
|
||
if (_showInventory &&
|
||
hasInsufficientStock)
|
||
Container(
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 8,
|
||
vertical: 4,
|
||
),
|
||
margin: const EdgeInsets.only(
|
||
bottom: 8,
|
||
),
|
||
decoration: BoxDecoration(
|
||
color: cs.errorContainer,
|
||
borderRadius: BorderRadius.circular(
|
||
4,
|
||
),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(
|
||
Icons.warning_amber_rounded,
|
||
size: 16,
|
||
color: cs.onErrorContainer,
|
||
),
|
||
const SizedBox(width: 8),
|
||
Expanded(
|
||
child: Text(
|
||
'موجودی کافی نیست! موجودی: ${_formatNumber(_getProductStock(item.productId) ?? 0)}، درخواست: ${_formatNumber(item.quantity)}',
|
||
style: TextStyle(
|
||
fontSize: isCompact
|
||
? 11
|
||
: 12,
|
||
color: cs.onErrorContainer,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
Row(
|
||
children: [
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment:
|
||
CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
item.productName ?? 'نامشخص',
|
||
style: TextStyle(
|
||
fontWeight: FontWeight.bold,
|
||
fontSize: isCompact
|
||
? 14
|
||
: 16,
|
||
),
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
'کد: ${item.productCode ?? '-'}',
|
||
style: TextStyle(
|
||
color: cs.onSurface
|
||
.withOpacity(0.7),
|
||
fontSize: 12,
|
||
),
|
||
),
|
||
// نمایش قیمت خرید (فقط اگر تنظیمات نمایش قیمت خرید فعال باشد)
|
||
if (_showPurchasePrice &&
|
||
item.basePurchasePriceMainUnit !=
|
||
null)
|
||
Padding(
|
||
padding:
|
||
const EdgeInsets.only(
|
||
top: 4,
|
||
),
|
||
child: Text(
|
||
'قیمت خرید: ${_formatNumber(item.basePurchasePriceMainUnit!)}',
|
||
style: TextStyle(
|
||
fontSize: 11,
|
||
color: cs.onSurface
|
||
.withOpacity(0.6),
|
||
fontStyle:
|
||
FontStyle.italic,
|
||
),
|
||
),
|
||
),
|
||
// نمایش موجودی (فقط اگر تنظیمات نمایش موجودی فعال باشد)
|
||
if (_showInventory &&
|
||
item.trackInventory &&
|
||
item.productId != null &&
|
||
item.extraInfo?['instance_id'] ==
|
||
null)
|
||
Builder(
|
||
builder: (context) {
|
||
final stock =
|
||
_getProductStock(
|
||
item.productId,
|
||
);
|
||
// اگر موجودی null است و در حال بارگذاری نیست، سعی کن بارگذاری کن
|
||
if (stock == null &&
|
||
!_isProductStockLoading(
|
||
item.productId,
|
||
) &&
|
||
_defaultWarehouseId !=
|
||
null) {
|
||
WidgetsBinding.instance
|
||
.addPostFrameCallback((
|
||
_,
|
||
) {
|
||
if (mounted &&
|
||
_showInventory) {
|
||
_scheduleStockLoads([
|
||
item.productId!,
|
||
]);
|
||
}
|
||
});
|
||
}
|
||
final isStockPending =
|
||
stock == null &&
|
||
_isProductStockLoading(
|
||
item.productId,
|
||
);
|
||
final hasInsufficientStock =
|
||
stock != null &&
|
||
stock < item.quantity;
|
||
return Padding(
|
||
padding:
|
||
const EdgeInsets.only(
|
||
top: 4,
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(
|
||
hasInsufficientStock
|
||
? Icons
|
||
.warning
|
||
: Icons
|
||
.inventory_2,
|
||
size: 14,
|
||
color:
|
||
hasInsufficientStock
|
||
? cs.error
|
||
: cs.onSurface
|
||
.withOpacity(
|
||
0.6,
|
||
),
|
||
),
|
||
const SizedBox(
|
||
width: 4,
|
||
),
|
||
Text(
|
||
stock != null
|
||
? 'موجودی: ${_formatNumber(stock)}'
|
||
: (isStockPending
|
||
? 'در حال بررسی موجودی...'
|
||
: 'موجودی نامشخص'),
|
||
style: TextStyle(
|
||
fontSize: 11,
|
||
color:
|
||
hasInsufficientStock
|
||
? cs.error
|
||
: cs.onSurface
|
||
.withOpacity(
|
||
0.6,
|
||
),
|
||
fontWeight:
|
||
hasInsufficientStock
|
||
? FontWeight
|
||
.bold
|
||
: FontWeight
|
||
.normal,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
},
|
||
),
|
||
],
|
||
),
|
||
),
|
||
IconButton(
|
||
icon: const Icon(
|
||
Icons.edit,
|
||
size: 20,
|
||
),
|
||
onPressed: () =>
|
||
_editCartItem(index),
|
||
tooltip: 'ویرایش',
|
||
visualDensity: isCompact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
IconButton(
|
||
icon: const Icon(
|
||
Icons.delete,
|
||
size: 20,
|
||
),
|
||
onPressed: () =>
|
||
_removeFromCart(index),
|
||
tooltip: 'حذف',
|
||
visualDensity: isCompact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
],
|
||
),
|
||
SizedBox(height: isCompact ? 6 : 8),
|
||
_buildCartItemQuantityAndTotals(
|
||
item: item,
|
||
index: index,
|
||
cs: cs,
|
||
compact: isCompact,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
);
|
||
|
||
final desktopBody = Row(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
// ستون اصلی: سبد خرید
|
||
Expanded(flex: 7, child: cartColumn),
|
||
// ستون کناری: مشتری، جمع و جزئیات سند
|
||
_buildDesktopCheckoutPanel(cs),
|
||
],
|
||
);
|
||
|
||
return _withParkedSalesBar(
|
||
_autoCreatePaymentDocument
|
||
? Stack(
|
||
children: [
|
||
Positioned.fill(child: desktopBody),
|
||
Align(
|
||
alignment: Alignment.bottomCenter,
|
||
child: QuickSalesPaymentDock(
|
||
key: ValueKey('payment-dock-$_activeSaleId'),
|
||
businessId: widget.businessId,
|
||
authStore: widget.authStore,
|
||
payments: _payments,
|
||
onChanged: _onPaymentsChanged,
|
||
invoiceTotal: _totalAmount,
|
||
paymentTarget: _paymentTargetAmount,
|
||
changeResolution: _validChangeResolution,
|
||
onConfigureChange: _openChangeResolutionDialog,
|
||
defaultCashRegisterId: _selectedCashRegisterId,
|
||
currencyUnit: _paymentCurrencyUnit,
|
||
currencyId: _defaultCurrencyId!,
|
||
decimalPlaces: _invoiceCurrencyDecimalPlaces,
|
||
enabled: !_isSaving,
|
||
onSave: () => _saveInvoice(print: false),
|
||
onSaveAndPrint: () => _saveInvoice(print: true),
|
||
),
|
||
),
|
||
],
|
||
)
|
||
: Column(
|
||
children: [
|
||
Expanded(child: desktopBody),
|
||
Material(
|
||
elevation: 3,
|
||
color: cs.surface,
|
||
child: _buildCheckoutButtons(cs),
|
||
),
|
||
],
|
||
),
|
||
compact: isCompact,
|
||
);
|
||
},
|
||
),
|
||
);
|
||
|
||
return KeyboardListener(
|
||
focusNode: _keyboardListenerFocus,
|
||
onKeyEvent: _handleKeyEvent,
|
||
child: scaffold,
|
||
);
|
||
}
|
||
|
||
Widget _buildMobileTabbedLayout(ColorScheme cs, {required bool isCompact}) {
|
||
return Column(
|
||
children: [
|
||
Material(
|
||
color: cs.surface,
|
||
child: TabBar(
|
||
controller: _mobileTabController,
|
||
tabs: const [
|
||
Tab(icon: Icon(Icons.shopping_cart_outlined), text: 'اقلام'),
|
||
Tab(icon: Icon(Icons.description_outlined), text: 'اطلاعات سند'),
|
||
Tab(icon: Icon(Icons.payments_outlined), text: 'پرداخت و ثبت'),
|
||
],
|
||
),
|
||
),
|
||
Expanded(
|
||
child: TabBarView(
|
||
controller: _mobileTabController,
|
||
children: [
|
||
_buildMobileItemsTab(cs, isCompact: isCompact),
|
||
_mobileTabsBuilt.contains(1)
|
||
? _buildMobileDocumentInfoTab(cs, isCompact: isCompact)
|
||
: const Center(child: CircularProgressIndicator()),
|
||
_mobileTabsBuilt.contains(2)
|
||
? _buildMobileCheckoutTab(cs)
|
||
: const Center(child: CircularProgressIndicator()),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildMobileItemsTab(ColorScheme cs, {required bool isCompact}) {
|
||
return Column(
|
||
children: [
|
||
Container(
|
||
padding: EdgeInsets.all(isCompact ? 12 : 16),
|
||
color: cs.surfaceContainerHighest,
|
||
child: Column(
|
||
children: [
|
||
Row(
|
||
children: [
|
||
if (_showInventory &&
|
||
_cartItems.any(
|
||
(item) => item.trackInventory && item.productId != null,
|
||
))
|
||
IconButton(
|
||
icon: _loadingStocksBulk
|
||
? const SizedBox(
|
||
width: 20,
|
||
height: 20,
|
||
child: CircularProgressIndicator(strokeWidth: 2),
|
||
)
|
||
: const Icon(Icons.refresh),
|
||
onPressed: _loadingStocksBulk
|
||
? null
|
||
: () => _refreshAllStocks(),
|
||
tooltip: 'بهروزرسانی موجودی',
|
||
),
|
||
Expanded(child: _buildBarcodeSearchField(compact: isCompact)),
|
||
],
|
||
),
|
||
],
|
||
),
|
||
),
|
||
if (_recentProducts.isNotEmpty && _cartItems.isEmpty)
|
||
Container(
|
||
padding: EdgeInsets.symmetric(
|
||
horizontal: isCompact ? 12 : 16,
|
||
vertical: 8,
|
||
),
|
||
color: cs.surfaceContainerHighest,
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
Icon(
|
||
Icons.history,
|
||
size: 18,
|
||
color: cs.onSurface.withOpacity(0.7),
|
||
),
|
||
const SizedBox(width: 8),
|
||
Text(
|
||
'محصولات اخیر',
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onSurface.withOpacity(0.7),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 8),
|
||
SizedBox(
|
||
height: 60,
|
||
child: ListView.builder(
|
||
scrollDirection: Axis.horizontal,
|
||
itemCount: _recentProducts.length,
|
||
itemBuilder: (context, index) {
|
||
final product = _recentProducts[index];
|
||
return Padding(
|
||
padding: const EdgeInsets.only(right: 8),
|
||
child: InkWell(
|
||
onTap: () => _onRecentProductTap(product),
|
||
child: AnimatedContainer(
|
||
duration: const Duration(milliseconds: 200),
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 12,
|
||
vertical: 8,
|
||
),
|
||
decoration: BoxDecoration(
|
||
color: cs.surface,
|
||
borderRadius: BorderRadius.circular(8),
|
||
border: Border.all(
|
||
color:
|
||
_recentProductLoadingId ==
|
||
_productIntId(product)
|
||
? cs.primary
|
||
: cs.outline.withOpacity(0.3),
|
||
),
|
||
),
|
||
child:
|
||
_recentProductLoadingId ==
|
||
_productIntId(product)
|
||
? SizedBox(
|
||
width: 80,
|
||
child: Center(
|
||
child: SizedBox(
|
||
width: 18,
|
||
height: 18,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2,
|
||
color: cs.primary,
|
||
),
|
||
),
|
||
),
|
||
)
|
||
: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment:
|
||
CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
product['name']?.toString() ?? 'نامشخص',
|
||
style: const TextStyle(
|
||
fontSize: 12,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
'${_formatNumber(_toNum(product['base_sales_price'] ?? product['sales_price']))}',
|
||
style: TextStyle(
|
||
fontSize: 11,
|
||
color: cs.primary,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
Expanded(
|
||
child: _cartItems.isEmpty
|
||
? Center(
|
||
child: AnimatedSwitcher(
|
||
duration: const Duration(milliseconds: 300),
|
||
child: Column(
|
||
key: ValueKey(_recentProducts.isEmpty),
|
||
mainAxisAlignment: MainAxisAlignment.center,
|
||
children: [
|
||
Icon(
|
||
Icons.shopping_cart_outlined,
|
||
size: 64,
|
||
color: cs.outline,
|
||
),
|
||
const SizedBox(height: 16),
|
||
Text(
|
||
'سبد خرید خالی است',
|
||
style: TextStyle(color: cs.outline),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
)
|
||
: ListView.builder(
|
||
padding: EdgeInsets.all(isCompact ? 6 : 8),
|
||
itemCount: _cartItems.length,
|
||
itemBuilder: (context, index) {
|
||
final item = _cartItems[index];
|
||
final hasInsufficientStock = _hasInsufficientStock(item);
|
||
return AnimatedContainer(
|
||
duration: const Duration(milliseconds: 300),
|
||
curve: Curves.easeInOut,
|
||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||
child: Card(
|
||
color: hasInsufficientStock
|
||
? cs.errorContainer.withOpacity(0.3)
|
||
: null,
|
||
child: InkWell(
|
||
onTap: () => _editCartItem(index),
|
||
child: Padding(
|
||
padding: EdgeInsets.all(isCompact ? 6 : 8),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
if (_showInventory && hasInsufficientStock)
|
||
Container(
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 8,
|
||
vertical: 4,
|
||
),
|
||
margin: const EdgeInsets.only(bottom: 8),
|
||
decoration: BoxDecoration(
|
||
color: cs.errorContainer,
|
||
borderRadius: BorderRadius.circular(4),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(
|
||
Icons.warning_amber_rounded,
|
||
size: 16,
|
||
color: cs.onErrorContainer,
|
||
),
|
||
const SizedBox(width: 8),
|
||
Expanded(
|
||
child: Text(
|
||
'موجودی کافی نیست! موجودی: ${_formatNumber(_getProductStock(item.productId) ?? 0)}، درخواست: ${_formatNumber(item.quantity)}',
|
||
style: TextStyle(
|
||
fontSize: isCompact ? 11 : 12,
|
||
color: cs.onErrorContainer,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
Row(
|
||
children: [
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment:
|
||
CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
item.productName ?? 'نامشخص',
|
||
style: TextStyle(
|
||
fontWeight: FontWeight.bold,
|
||
fontSize: isCompact ? 14 : 16,
|
||
),
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
'کد: ${item.productCode ?? '-'}',
|
||
style: TextStyle(
|
||
color: cs.onSurface.withOpacity(
|
||
0.7,
|
||
),
|
||
fontSize: 12,
|
||
),
|
||
),
|
||
if (_showPurchasePrice &&
|
||
item.basePurchasePriceMainUnit !=
|
||
null)
|
||
Padding(
|
||
padding: const EdgeInsets.only(
|
||
top: 4,
|
||
),
|
||
child: Text(
|
||
'قیمت خرید: ${_formatNumber(item.basePurchasePriceMainUnit!)}',
|
||
style: TextStyle(
|
||
fontSize: 11,
|
||
color: cs.onSurface
|
||
.withOpacity(0.6),
|
||
fontStyle: FontStyle.italic,
|
||
),
|
||
),
|
||
),
|
||
if (_showInventory &&
|
||
item.trackInventory &&
|
||
item.productId != null &&
|
||
item.extraInfo?['instance_id'] ==
|
||
null)
|
||
Builder(
|
||
builder: (context) {
|
||
final stock = _getProductStock(
|
||
item.productId,
|
||
);
|
||
if (stock == null &&
|
||
!_isProductStockLoading(
|
||
item.productId,
|
||
) &&
|
||
_defaultWarehouseId !=
|
||
null) {
|
||
WidgetsBinding.instance
|
||
.addPostFrameCallback((
|
||
_,
|
||
) {
|
||
if (mounted &&
|
||
_showInventory) {
|
||
_scheduleStockLoads([
|
||
item.productId!,
|
||
]);
|
||
}
|
||
});
|
||
}
|
||
final isStockPending =
|
||
stock == null &&
|
||
_isProductStockLoading(
|
||
item.productId,
|
||
);
|
||
final insufficient =
|
||
stock != null &&
|
||
stock < item.quantity;
|
||
return Padding(
|
||
padding:
|
||
const EdgeInsets.only(
|
||
top: 4,
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(
|
||
insufficient
|
||
? Icons.warning
|
||
: Icons.inventory_2,
|
||
size: 14,
|
||
color: insufficient
|
||
? cs.error
|
||
: cs.onSurface
|
||
.withOpacity(
|
||
0.6,
|
||
),
|
||
),
|
||
const SizedBox(width: 4),
|
||
Text(
|
||
stock != null
|
||
? 'موجودی: ${_formatNumber(stock)}'
|
||
: (isStockPending
|
||
? 'در حال بررسی موجودی...'
|
||
: 'موجودی نامشخص'),
|
||
style: TextStyle(
|
||
fontSize: 11,
|
||
color: insufficient
|
||
? cs.error
|
||
: cs.onSurface
|
||
.withOpacity(
|
||
0.6,
|
||
),
|
||
fontWeight:
|
||
insufficient
|
||
? FontWeight.bold
|
||
: FontWeight
|
||
.normal,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
},
|
||
),
|
||
],
|
||
),
|
||
),
|
||
IconButton(
|
||
icon: const Icon(Icons.edit, size: 20),
|
||
onPressed: () => _editCartItem(index),
|
||
tooltip: 'ویرایش',
|
||
visualDensity: isCompact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
IconButton(
|
||
icon: const Icon(Icons.delete, size: 20),
|
||
onPressed: () => _removeFromCart(index),
|
||
tooltip: 'حذف',
|
||
visualDensity: isCompact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
],
|
||
),
|
||
SizedBox(height: isCompact ? 6 : 8),
|
||
_buildCartItemQuantityAndTotals(
|
||
item: item,
|
||
index: index,
|
||
cs: cs,
|
||
compact: isCompact,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildMobileDocumentInfoTab(
|
||
ColorScheme cs, {
|
||
required bool isCompact,
|
||
}) {
|
||
return SingleChildScrollView(
|
||
padding: EdgeInsets.all(isCompact ? 12 : 16),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
_buildCustomerSelector(),
|
||
const SizedBox(height: 12),
|
||
_buildDocumentDateAndDescription(isMobile: true, compact: isCompact),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildMobileCheckoutTab(ColorScheme cs) {
|
||
return Column(
|
||
children: [
|
||
Expanded(
|
||
child: ListView(
|
||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
|
||
children: [
|
||
_buildCheckoutScrollBody(
|
||
cs,
|
||
includeCustomer: false,
|
||
includeDocumentMeta: false,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
Material(
|
||
elevation: 3,
|
||
color: cs.surface,
|
||
child: SafeArea(top: false, child: _buildCheckoutButtons(cs)),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildBarcodeSearchField({bool compact = false}) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
final filterBtn = IconButton(
|
||
icon: Icon(
|
||
_selectedCategoryId != null
|
||
? Icons.filter_alt
|
||
: Icons.filter_alt_outlined,
|
||
),
|
||
tooltip: 'فیلتر دستهبندی',
|
||
color: _selectedCategoryId != null
|
||
? cs.primary
|
||
: cs.onSurface.withOpacity(0.6),
|
||
onPressed: () => _showCategoryFilter(context),
|
||
visualDensity: compact ? VisualDensity.compact : VisualDensity.standard,
|
||
);
|
||
|
||
Widget searchField = CompositedTransformTarget(
|
||
link: _barcodeFieldLayerLink,
|
||
child: TextField(
|
||
controller: _barcodeController,
|
||
focusNode: _barcodeFocus,
|
||
enabled: !_barcodeSearching,
|
||
decoration: InputDecoration(
|
||
labelText: compact ? 'جستجوی کالا' : 'بارکد / کد / نام محصول',
|
||
hintText: compact
|
||
? 'کد، نام یا بارکد'
|
||
: 'اسکن یا وارد کردن بارکد، کد یا نام',
|
||
prefixIcon: compact ? null : Icon(Icons.qr_code_scanner),
|
||
isDense: compact,
|
||
border: const OutlineInputBorder(),
|
||
suffixIconConstraints: BoxConstraints(
|
||
minHeight: compact ? 40 : 48,
|
||
minWidth: compact ? 120 : 160,
|
||
),
|
||
suffixIcon: Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
if (_barcodeSearching)
|
||
Padding(
|
||
padding: const EdgeInsetsDirectional.only(end: 4),
|
||
child: SizedBox(
|
||
width: compact ? 18 : 20,
|
||
height: compact ? 18 : 20,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2,
|
||
color: cs.primary,
|
||
),
|
||
),
|
||
),
|
||
if (_canCreateProducts)
|
||
IconButton(
|
||
icon: Icon(Icons.add),
|
||
tooltip: 'افزودن کالای جدید',
|
||
onPressed: () => _openAddProductDialog(),
|
||
visualDensity: compact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
if (_supportsCameraScanButton)
|
||
IconButton(
|
||
icon: const Icon(Icons.photo_camera_outlined),
|
||
tooltip: 'اسکن بارکد یا QR با دوربین',
|
||
onPressed: _scanBarcodeWithCamera,
|
||
visualDensity: compact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
if (_canCreateProducts &&
|
||
_lastFailedSearchQuery != null &&
|
||
_lastFailedSearchQuery!.isNotEmpty)
|
||
IconButton(
|
||
icon: Icon(
|
||
Icons.add_circle,
|
||
color: SemanticColorResolver.positive(context),
|
||
),
|
||
tooltip: 'افزودن کالای جدید: $_lastFailedSearchQuery',
|
||
onPressed: () =>
|
||
_openAddProductDialog(presetName: _lastFailedSearchQuery),
|
||
visualDensity: compact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
IconButton(
|
||
icon: const Icon(Icons.search),
|
||
onPressed: () => _searchByBarcode(_barcodeController.text),
|
||
tooltip: 'جستجو',
|
||
visualDensity: compact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
onSubmitted: (value) {
|
||
final action = resolveQuickSalesProductSearchSubmitAction(
|
||
input: value,
|
||
loadedQuery: _barcodeSuggestionsQuery,
|
||
suggestionCount: _barcodeSuggestions.length,
|
||
hasMoreSuggestions: _barcodeSuggestionsHasMore,
|
||
navigatedByKeyboard: _barcodeSuggestionNavigatedByKeyboard,
|
||
);
|
||
switch (action) {
|
||
case QuickSalesProductSearchSubmitAction.selectSuggestion:
|
||
unawaited(_selectHighlightedBarcodeSuggestion());
|
||
break;
|
||
case QuickSalesProductSearchSubmitAction.searchField:
|
||
unawaited(
|
||
_searchByBarcode(value, showMultipleResultsDialog: false),
|
||
);
|
||
break;
|
||
case QuickSalesProductSearchSubmitAction.waitForSuggestionSelection:
|
||
break;
|
||
}
|
||
},
|
||
onChanged: (value) {
|
||
if (_lastFailedSearchQuery != null &&
|
||
value != _lastFailedSearchQuery) {
|
||
setState(() {
|
||
_lastFailedSearchQuery = null;
|
||
});
|
||
}
|
||
if (_isDesktopLike) {
|
||
if (!shouldShowProductSearchSuggestions(value)) {
|
||
_clearBarcodeSuggestions();
|
||
} else {
|
||
if (_barcodeOverlayEntry == null && _barcodeFocus.hasFocus) {
|
||
_showBarcodeOverlay();
|
||
}
|
||
_scheduleBarcodeSuggestionSearch(value);
|
||
}
|
||
}
|
||
},
|
||
textInputAction: TextInputAction.search,
|
||
),
|
||
);
|
||
|
||
final categoryChip = _selectedCategoryId != null
|
||
? Chip(
|
||
label: Text(
|
||
_getCategoryLabel(_selectedCategoryId!),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
onDeleted: () {
|
||
setState(() {
|
||
_selectedCategoryId = null;
|
||
});
|
||
},
|
||
deleteIcon: const Icon(Icons.close, size: 18),
|
||
avatar: const Icon(Icons.category, size: 18),
|
||
materialTapTargetSize: compact
|
||
? MaterialTapTargetSize.shrinkWrap
|
||
: MaterialTapTargetSize.padded,
|
||
visualDensity: compact
|
||
? VisualDensity.compact
|
||
: VisualDensity.standard,
|
||
)
|
||
: null;
|
||
|
||
if (compact) {
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
Row(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
filterBtn,
|
||
Expanded(child: searchField),
|
||
],
|
||
),
|
||
if (categoryChip != null) ...[
|
||
const SizedBox(height: 6),
|
||
Align(
|
||
alignment: AlignmentDirectional.centerStart,
|
||
child: categoryChip,
|
||
),
|
||
],
|
||
],
|
||
);
|
||
}
|
||
|
||
return Row(
|
||
children: [
|
||
filterBtn,
|
||
if (categoryChip != null)
|
||
Flexible(
|
||
child: Padding(
|
||
padding: const EdgeInsetsDirectional.only(end: 8),
|
||
child: categoryChip,
|
||
),
|
||
),
|
||
Expanded(child: searchField),
|
||
],
|
||
);
|
||
}
|
||
|
||
String _getCategoryLabel(int categoryId) {
|
||
final node = findCategoryNode(_categoryTree, categoryId);
|
||
return node?.label ?? 'دستهبندی';
|
||
}
|
||
|
||
void _showCategoryFilter(BuildContext context) {
|
||
if (_categoryTree.isEmpty && !_loadingCategories) {
|
||
unawaited(_loadCategories());
|
||
}
|
||
final screenWidth = MediaQuery.of(context).size.width;
|
||
final isMobile = screenWidth < ResponsiveHelper.shellPersistentNavMinWidth;
|
||
|
||
if (isMobile) {
|
||
// موبایل: bottom sheet
|
||
showModalBottomSheet(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
builder: (ctx) {
|
||
return Container(
|
||
padding: const EdgeInsets.all(16),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
Text(
|
||
'انتخاب دستهبندی',
|
||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||
fontWeight: FontWeight.w600,
|
||
),
|
||
),
|
||
const Spacer(),
|
||
IconButton(
|
||
onPressed: () => Navigator.pop(ctx),
|
||
icon: const Icon(Icons.close),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 16),
|
||
SizedBox(
|
||
height: 400,
|
||
child: _loadingCategories
|
||
? const Center(child: CircularProgressIndicator())
|
||
: CategoryTreeWidget(
|
||
categories: _categoryTree,
|
||
selectedCategoryId: _selectedCategoryId,
|
||
onCategorySelected: (categoryId) {
|
||
setState(() {
|
||
_selectedCategoryId = categoryId;
|
||
});
|
||
Navigator.pop(ctx);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
},
|
||
);
|
||
} else {
|
||
// دسکتاپ: Dialog
|
||
showDialog(
|
||
context: context,
|
||
builder: (ctx) {
|
||
return Dialog(
|
||
child: Container(
|
||
width: 600,
|
||
height: 500,
|
||
child: Column(
|
||
children: [
|
||
Container(
|
||
padding: const EdgeInsets.all(16),
|
||
decoration: BoxDecoration(
|
||
color: Theme.of(
|
||
context,
|
||
).colorScheme.surfaceContainerHighest,
|
||
border: Border(
|
||
bottom: BorderSide(
|
||
color: Theme.of(
|
||
context,
|
||
).colorScheme.outline.withOpacity(0.2),
|
||
),
|
||
),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Text(
|
||
'انتخاب دستهبندی',
|
||
style: Theme.of(context).textTheme.titleLarge
|
||
?.copyWith(fontWeight: FontWeight.w600),
|
||
),
|
||
const Spacer(),
|
||
IconButton(
|
||
onPressed: () => Navigator.pop(ctx),
|
||
icon: const Icon(Icons.close),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
Expanded(
|
||
child: _loadingCategories
|
||
? const Center(child: CircularProgressIndicator())
|
||
: CategoryTreeWidget(
|
||
categories: _categoryTree,
|
||
selectedCategoryId: _selectedCategoryId,
|
||
onCategorySelected: (categoryId) {
|
||
setState(() {
|
||
_selectedCategoryId = categoryId;
|
||
});
|
||
Navigator.pop(ctx);
|
||
},
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
},
|
||
);
|
||
}
|
||
}
|
||
|
||
Widget _buildDesktopCheckoutPanel(ColorScheme cs) {
|
||
return Container(
|
||
width: 384,
|
||
color: cs.surfaceContainerHighest,
|
||
child: Scrollbar(
|
||
thumbVisibility: true,
|
||
child: SingleChildScrollView(
|
||
padding: EdgeInsets.fromLTRB(
|
||
12,
|
||
12,
|
||
12,
|
||
_autoCreatePaymentDocument
|
||
? QuickSalesPaymentDock.desktopSummaryHeight + 8
|
||
: 8,
|
||
),
|
||
child: _buildCheckoutScrollBody(
|
||
cs,
|
||
includeCustomer: true,
|
||
includeDocumentMeta: true,
|
||
includePayment: false,
|
||
includeTotal: false,
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildCheckoutScrollBody(
|
||
ColorScheme cs, {
|
||
required bool includeCustomer,
|
||
required bool includeDocumentMeta,
|
||
bool includePayment = true,
|
||
bool includeTotal = true,
|
||
}) {
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
if (includeCustomer) ...[
|
||
_buildCustomerSelector(dense: true),
|
||
const SizedBox(height: 10),
|
||
],
|
||
if (includeTotal) ...[
|
||
_buildCheckoutTotalHero(cs),
|
||
const SizedBox(height: 4),
|
||
],
|
||
_buildCheckoutDiscountBlock(cs),
|
||
const SizedBox(height: 10),
|
||
if (includePayment) ...[
|
||
_buildPaymentSection(cs),
|
||
const SizedBox(height: 4),
|
||
],
|
||
_buildCheckoutDetailsTile(cs, includeDocumentMeta: includeDocumentMeta),
|
||
if (!includePayment) ...[
|
||
const SizedBox(height: 8),
|
||
_buildDesktopShareControls(cs),
|
||
],
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildDesktopShareControls(ColorScheme cs) {
|
||
final t = AppLocalizations.of(context);
|
||
if (!_autoCreatePaymentDocument) return _buildShareSection(cs, t);
|
||
if (_remainingAmount <= 0 || _isOverpaid) return const SizedBox.shrink();
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
SwitchListTile.adaptive(
|
||
contentPadding: EdgeInsets.zero,
|
||
dense: true,
|
||
title: Tooltip(
|
||
message: t.quickSalesPayShareRemainingHint,
|
||
child: Text(t.quickSalesPayShareRemaining),
|
||
),
|
||
value: _shareRemainingEnabled,
|
||
onChanged: _isSaving
|
||
? null
|
||
: (value) {
|
||
setState(() {
|
||
_shareRemainingEnabled = value;
|
||
if (value) _syncShareChannelDefaults();
|
||
});
|
||
},
|
||
),
|
||
if (_shareRemainingEnabled) _buildShareSection(cs, t),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildCheckoutTotalHero(ColorScheme cs) {
|
||
final t = AppLocalizations.of(context);
|
||
return Material(
|
||
color: cs.primaryContainer.withValues(alpha: 0.55),
|
||
borderRadius: BorderRadius.circular(12),
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Text(
|
||
t.invoiceSummaryTotal,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.labelLarge?.copyWith(color: cs.onPrimaryContainer),
|
||
),
|
||
const SizedBox(height: 2),
|
||
Text(
|
||
_formatNumber(_totalAmount),
|
||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||
fontWeight: FontWeight.w800,
|
||
color: cs.onPrimaryContainer,
|
||
),
|
||
),
|
||
if (_totalDiscount > 0)
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 2),
|
||
child: Text(
|
||
'${t.invoiceSummaryDiscount}: -${_formatNumber(_totalDiscount)}',
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.onPrimaryContainer),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
bool get _hasGlobalDiscount {
|
||
final v = _parsedGlobalDiscountValue;
|
||
return v != null && v > 0;
|
||
}
|
||
|
||
Widget _buildCheckoutDiscountBlock(ColorScheme cs) {
|
||
final t = AppLocalizations.of(context);
|
||
final expanded = _checkoutDiscountExpanded || _hasGlobalDiscount;
|
||
if (!expanded) {
|
||
return Align(
|
||
alignment: AlignmentDirectional.centerStart,
|
||
child: TextButton.icon(
|
||
onPressed: _isSaving
|
||
? null
|
||
: () => setState(() => _checkoutDiscountExpanded = true),
|
||
icon: const Icon(Icons.percent, size: 18),
|
||
label: Text(t.invoiceGlobalDiscountSection),
|
||
style: TextButton.styleFrom(
|
||
visualDensity: VisualDensity.compact,
|
||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
return _buildGlobalDiscountSection(cs, showHeading: false);
|
||
}
|
||
|
||
bool get _forceCheckoutDetails =>
|
||
_enableWarehouseDocument && _defaultWarehouseId == null;
|
||
|
||
Widget _buildCheckoutDetailsTile(
|
||
ColorScheme cs, {
|
||
required bool includeDocumentMeta,
|
||
}) {
|
||
final t = AppLocalizations.of(context);
|
||
return Theme(
|
||
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
|
||
child: ExpansionTile(
|
||
key: ValueKey('qs-details-$_forceCheckoutDetails'),
|
||
initiallyExpanded: true,
|
||
tilePadding: EdgeInsets.zero,
|
||
childrenPadding: const EdgeInsets.only(bottom: 8),
|
||
visualDensity: VisualDensity.compact,
|
||
title: Text(
|
||
t.quickSalesCheckoutDetails,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
|
||
),
|
||
subtitle: _forceCheckoutDetails
|
||
? Text(
|
||
t.quickSalesCheckoutWarehouseRequired,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.error),
|
||
)
|
||
: null,
|
||
children: [
|
||
if (includeDocumentMeta) ...[
|
||
_buildDocumentDateAndDescription(isMobile: true, compact: true),
|
||
const SizedBox(height: 8),
|
||
],
|
||
_buildCheckoutBreakdown(cs, t),
|
||
const SizedBox(height: 10),
|
||
WarehouseComboboxWidget(
|
||
businessId: widget.businessId,
|
||
selectedWarehouseId: _defaultWarehouseId,
|
||
onChanged: _onWarehouseForInvoiceChanged,
|
||
label: 'انبار اقلام',
|
||
hintText: 'انتخاب انبار برای اقلام فاکتور',
|
||
isRequired: _enableWarehouseDocument,
|
||
selectDefaultWhenUnset: true,
|
||
),
|
||
const SizedBox(height: 4),
|
||
SwitchListTile.adaptive(
|
||
contentPadding: EdgeInsets.zero,
|
||
dense: true,
|
||
title: Tooltip(
|
||
message: t.quickSalesAutoCreateReceiptSwitchHint,
|
||
child: Text(t.quickSalesAutoCreateReceiptSwitch),
|
||
),
|
||
value: _autoCreatePaymentDocument,
|
||
onChanged: _isSaving ? null : _onAutoCreatePaymentDocumentChanged,
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildCheckoutBreakdown(ColorScheme cs, AppLocalizations t) {
|
||
return Column(
|
||
children: [
|
||
_buildSummaryRow('تعداد اقلام', '${_cartItems.length}'),
|
||
_buildSummaryRow(
|
||
t.invoiceSummarySubtotal,
|
||
_formatNumber(_subtotalAmount),
|
||
),
|
||
if (_totalDiscount > 0)
|
||
_buildSummaryRow(
|
||
t.invoiceSummaryDiscount,
|
||
'-${_formatNumber(_totalDiscount)}',
|
||
),
|
||
if (_totalTax > 0)
|
||
_buildSummaryRow(t.invoiceSummaryTax, _formatNumber(_totalTax)),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildGlobalDiscountSection(
|
||
ColorScheme cs, {
|
||
bool showHeading = true,
|
||
}) {
|
||
final t = AppLocalizations.of(context);
|
||
final g = _totalsWithGlobal;
|
||
final lineDisc = _lineDiscountOnly;
|
||
final narrow = MediaQuery.sizeOf(context).width < _compactBreakpoint;
|
||
return Card(
|
||
margin: EdgeInsets.zero,
|
||
child: Padding(
|
||
padding: const EdgeInsets.all(10),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
if (showHeading && !narrow) ...[
|
||
Text(
|
||
t.invoiceGlobalDiscountSection,
|
||
style: Theme.of(context).textTheme.titleSmall,
|
||
),
|
||
const SizedBox(height: 8),
|
||
],
|
||
if (narrow)
|
||
DropdownButtonFormField<String>(
|
||
value: _globalDiscountType,
|
||
isExpanded: true,
|
||
decoration: InputDecoration(
|
||
labelText: t.invoiceGlobalDiscountSection,
|
||
isDense: true,
|
||
border: const OutlineInputBorder(),
|
||
),
|
||
items: [
|
||
DropdownMenuItem(
|
||
value: 'percent',
|
||
child: Text(t.invoiceGlobalDiscountTypePercent),
|
||
),
|
||
DropdownMenuItem(
|
||
value: 'amount',
|
||
child: Text(t.invoiceGlobalDiscountTypeAmount),
|
||
),
|
||
],
|
||
onChanged: (v) {
|
||
if (v != null) {
|
||
setState(() => _globalDiscountType = v);
|
||
}
|
||
},
|
||
)
|
||
else
|
||
SegmentedButton<String>(
|
||
segments: [
|
||
ButtonSegment<String>(
|
||
value: 'percent',
|
||
label: Text(t.invoiceGlobalDiscountTypePercent),
|
||
),
|
||
ButtonSegment<String>(
|
||
value: 'amount',
|
||
label: Text(t.invoiceGlobalDiscountTypeAmount),
|
||
),
|
||
],
|
||
selected: {_globalDiscountType},
|
||
onSelectionChanged: (s) {
|
||
setState(() {
|
||
_globalDiscountType = s.first;
|
||
});
|
||
},
|
||
),
|
||
const SizedBox(height: 8),
|
||
TextField(
|
||
controller: _globalDiscountValueController,
|
||
keyboardType: const TextInputType.numberWithOptions(
|
||
decimal: true,
|
||
),
|
||
decoration: InputDecoration(
|
||
labelText: t.invoiceGlobalDiscountValueLabel,
|
||
isDense: true,
|
||
border: const OutlineInputBorder(),
|
||
),
|
||
),
|
||
const SizedBox(height: 6),
|
||
Text(
|
||
t.invoiceGlobalDiscountLineDiscountHint(_formatNumber(lineDisc)),
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.onSurfaceVariant),
|
||
),
|
||
if (g != null && g.globalDiscountAmount > 0)
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 4),
|
||
child: Text(
|
||
t.invoiceGlobalDiscountAmountComputedHint(
|
||
_formatNumber(g.globalDiscountAmount),
|
||
),
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.onSurfaceVariant),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildPaymentSection(ColorScheme cs) {
|
||
final t = AppLocalizations.of(context);
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
'پرداخت',
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w700),
|
||
),
|
||
const SizedBox(height: 8),
|
||
if (_autoCreatePaymentDocument) ...[
|
||
QuickSalesPaymentComposer(
|
||
key: ValueKey(_activeSaleId),
|
||
businessId: widget.businessId,
|
||
payments: _payments,
|
||
onChanged: _onPaymentsChanged,
|
||
cashFollowsTotal: _cashFollowsTotal,
|
||
onCashFollowsTotalChanged: (v) {
|
||
if (v == _cashFollowsTotal) return;
|
||
setState(() => _cashFollowsTotal = v);
|
||
},
|
||
invoiceTotal: _paymentTargetAmount,
|
||
defaultCashRegisterId: _selectedCashRegisterId,
|
||
enabled: !_isSaving,
|
||
currencyId: _defaultCurrencyId,
|
||
currencyUnit: _paymentCurrencyUnit,
|
||
decimalPlaces: _invoiceCurrencyDecimalPlaces,
|
||
authStore: widget.authStore,
|
||
calendarController: widget.calendarController,
|
||
isAnonymousCustomer: _isAnonymousSelected,
|
||
),
|
||
if (_isOverpaid) ...[
|
||
const SizedBox(height: 8),
|
||
Card(
|
||
color: cs.errorContainer,
|
||
margin: EdgeInsets.zero,
|
||
child: ListTile(
|
||
dense: true,
|
||
leading: Icon(
|
||
_validChangeResolution == null
|
||
? Icons.rule_folder_outlined
|
||
: Icons.edit_outlined,
|
||
color: cs.onErrorContainer,
|
||
),
|
||
title: Text(
|
||
_validChangeResolution == null
|
||
? 'تعیین تکلیف مبلغ اضافهدریافت'
|
||
: 'برگشت ${_formatNumber(_validChangeResolution!.returnedAmount)} • بستانکاری ${_formatNumber(_validChangeResolution!.creditAmount)}',
|
||
style: TextStyle(
|
||
color: cs.onErrorContainer,
|
||
fontWeight: FontWeight.w700,
|
||
),
|
||
),
|
||
subtitle: Text(
|
||
'${_formatNumber(_changeAmount)} $_paymentCurrencyUnit',
|
||
style: TextStyle(color: cs.onErrorContainer),
|
||
),
|
||
onTap: _isSaving
|
||
? null
|
||
: () => unawaited(_openChangeResolutionDialog()),
|
||
),
|
||
),
|
||
],
|
||
if (_remainingAmount > 0 && !_isOverpaid) ...[
|
||
SwitchListTile.adaptive(
|
||
contentPadding: EdgeInsets.zero,
|
||
dense: true,
|
||
title: Tooltip(
|
||
message: t.quickSalesPayShareRemainingHint,
|
||
child: Text(t.quickSalesPayShareRemaining),
|
||
),
|
||
value: _shareRemainingEnabled,
|
||
onChanged: _isSaving
|
||
? null
|
||
: (v) {
|
||
setState(() {
|
||
_shareRemainingEnabled = v;
|
||
if (v) _syncShareChannelDefaults();
|
||
});
|
||
},
|
||
),
|
||
if (_shareRemainingEnabled) _buildShareSection(cs, t),
|
||
],
|
||
] else
|
||
_buildShareSection(cs, t),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildShareSection(ColorScheme cs, AppLocalizations t) {
|
||
final gatewayIds = _shareGateways
|
||
.map((g) => (g['id'] as num?)?.toInt())
|
||
.whereType<int>()
|
||
.toSet();
|
||
final dropdownValue =
|
||
_shareGatewayId != null && gatewayIds.contains(_shareGatewayId)
|
||
? _shareGatewayId
|
||
: null;
|
||
final hasPhone = _selectedCustomerPhone != null;
|
||
final hasEmail = _selectedCustomerEmail != null;
|
||
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Text(
|
||
t.quickSalesShareSectionTitle,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
|
||
),
|
||
const SizedBox(height: 4),
|
||
SwitchListTile.adaptive(
|
||
contentPadding: EdgeInsets.zero,
|
||
dense: true,
|
||
title: Tooltip(
|
||
message: t.quickSalesShareOnlinePaymentHint,
|
||
child: Text(t.quickSalesShareOnlinePayment),
|
||
),
|
||
value: _shareOnlinePaymentEnabled,
|
||
onChanged: _isSaving || _loadingShareGateways
|
||
? null
|
||
: (v) {
|
||
setState(() {
|
||
_shareOnlinePaymentEnabled = v;
|
||
if (!v) _shareGatewayId = null;
|
||
});
|
||
},
|
||
),
|
||
if (_loadingShareGateways)
|
||
const LinearProgressIndicator()
|
||
else if (_shareOnlinePaymentEnabled && _shareGateways.isEmpty)
|
||
Text(
|
||
t.quickSalesShareNoGateway,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.error),
|
||
)
|
||
else if (_shareOnlinePaymentEnabled) ...[
|
||
DropdownButtonFormField<int?>(
|
||
value: dropdownValue,
|
||
decoration: InputDecoration(
|
||
labelText: t.quickSalesShareGatewayLabel,
|
||
border: const OutlineInputBorder(),
|
||
isDense: true,
|
||
),
|
||
items: [
|
||
for (final g in _shareGateways)
|
||
DropdownMenuItem<int?>(
|
||
value: (g['id'] as num?)?.toInt(),
|
||
child: Text(
|
||
'${g['display_name'] ?? g['id']}${g['provider'] != null ? ' (${g['provider']})' : ''}',
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
),
|
||
],
|
||
onChanged: _isSaving || !_shareOnlinePaymentEnabled
|
||
? null
|
||
: (v) => setState(() => _shareGatewayId = v),
|
||
),
|
||
const SizedBox(height: 8),
|
||
],
|
||
Wrap(
|
||
spacing: 8,
|
||
runSpacing: 4,
|
||
children: [
|
||
FilterChip(
|
||
label: Text(t.quickSalesShareChannelSms),
|
||
selected: _shareSendSms,
|
||
onSelected: _isSaving || !hasPhone
|
||
? null
|
||
: (v) => setState(() => _shareSendSms = v),
|
||
),
|
||
FilterChip(
|
||
label: Text(t.quickSalesShareChannelEmail),
|
||
selected: _shareSendEmail,
|
||
onSelected: _isSaving || !hasEmail
|
||
? null
|
||
: (v) => setState(() => _shareSendEmail = v),
|
||
),
|
||
FilterChip(
|
||
label: Text(t.quickSalesShareChannelNative),
|
||
selected: _shareViaNativeShare,
|
||
onSelected: _isSaving
|
||
? null
|
||
: (v) => setState(() => _shareViaNativeShare = v),
|
||
),
|
||
],
|
||
),
|
||
if (!hasPhone)
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 4),
|
||
child: Text(
|
||
t.quickSalesShareNoPhoneHint,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.error),
|
||
),
|
||
),
|
||
if (!hasEmail)
|
||
Padding(
|
||
padding: const EdgeInsets.only(top: 2),
|
||
child: Text(
|
||
t.quickSalesShareNoEmailHint,
|
||
style: Theme.of(
|
||
context,
|
||
).textTheme.bodySmall?.copyWith(color: cs.onSurfaceVariant),
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
|
||
Widget _buildCheckoutButtons(ColorScheme cs) {
|
||
Widget saveSpinner({double size = 18}) => SizedBox(
|
||
width: size,
|
||
height: size,
|
||
child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary),
|
||
);
|
||
|
||
return Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 12),
|
||
child: Row(
|
||
children: [
|
||
Expanded(
|
||
child: SizedBox(
|
||
height: 48,
|
||
child: OutlinedButton.icon(
|
||
onPressed: _isSaving ? null : () => _saveInvoice(print: false),
|
||
icon: _saveAction == _QuickSalesSaveAction.save
|
||
? SizedBox(
|
||
width: 18,
|
||
height: 18,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2,
|
||
color: cs.primary,
|
||
),
|
||
)
|
||
: const Icon(Icons.save, size: 20),
|
||
label: const Text('ثبت'),
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(width: 8),
|
||
Expanded(
|
||
flex: 2,
|
||
child: SizedBox(
|
||
height: 48,
|
||
child: ElevatedButton.icon(
|
||
onPressed: _isSaving ? null : () => _saveInvoice(print: true),
|
||
icon: _saveAction == _QuickSalesSaveAction.saveAndPrint
|
||
? saveSpinner()
|
||
: const Icon(Icons.print, size: 20),
|
||
label: const Text('ثبت و چاپ'),
|
||
style: ElevatedButton.styleFrom(
|
||
backgroundColor: cs.primary,
|
||
foregroundColor: cs.onPrimary,
|
||
),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildSummaryRow(
|
||
String label,
|
||
String value, {
|
||
bool isTotal = false,
|
||
bool isWarning = false,
|
||
}) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
return Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||
child: Row(
|
||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||
children: [
|
||
Text(
|
||
label,
|
||
style: TextStyle(
|
||
fontSize: isTotal ? 16 : 14,
|
||
fontWeight: isTotal ? FontWeight.bold : FontWeight.normal,
|
||
color: isWarning ? cs.error : null,
|
||
),
|
||
),
|
||
Text(
|
||
value,
|
||
style: TextStyle(
|
||
fontSize: isTotal ? 18 : 14,
|
||
fontWeight: FontWeight.bold,
|
||
color: isTotal
|
||
? cs.primary
|
||
: (isWarning ? cs.error : cs.onSurface),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
String _formatNumber(num value) {
|
||
return formatWithThousands(
|
||
value,
|
||
decimalPlaces: _invoiceCurrencyDecimalPlaces,
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Dialog برای ویرایش اقلام سبد خرید
|
||
class _CartItemEditDialog extends StatefulWidget {
|
||
final InvoiceLineItem item;
|
||
final int currencyDecimalPlaces;
|
||
final bool allowEditUnitPrice;
|
||
|
||
const _CartItemEditDialog({
|
||
required this.item,
|
||
required this.currencyDecimalPlaces,
|
||
this.allowEditUnitPrice = true,
|
||
});
|
||
|
||
@override
|
||
State<_CartItemEditDialog> createState() => _CartItemEditDialogState();
|
||
}
|
||
|
||
class _CartItemEditDialogState extends State<_CartItemEditDialog> {
|
||
late TextEditingController _quantityController;
|
||
late TextEditingController _priceController;
|
||
late TextEditingController _discountController;
|
||
late String _discountType;
|
||
late TextEditingController _taxRateController;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_quantityController = TextEditingController(
|
||
text: number_utils.formatNumberForInput(widget.item.quantity),
|
||
);
|
||
_priceController = TextEditingController(
|
||
text: number_utils.formatNumberForInput(widget.item.unitPrice),
|
||
);
|
||
_discountController = TextEditingController(
|
||
text: number_utils.formatNumberForInput(widget.item.discountValue),
|
||
);
|
||
_discountType = widget.item.discountType;
|
||
_taxRateController = TextEditingController(
|
||
text: number_utils.formatNumberForInput(widget.item.taxRate),
|
||
);
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
_quantityController.dispose();
|
||
_priceController.dispose();
|
||
_discountController.dispose();
|
||
_taxRateController.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
InvoiceLineItem _buildUpdatedItem() {
|
||
final quantityValue = number_utils.parseFormattedNumber(
|
||
_quantityController.text,
|
||
);
|
||
final priceValue = number_utils.parseFormattedNumber(_priceController.text);
|
||
final discountValue = number_utils.parseFormattedNumber(
|
||
_discountController.text,
|
||
);
|
||
final taxRateValue = number_utils.parseFormattedNumber(
|
||
_taxRateController.text,
|
||
);
|
||
|
||
final quantity = (quantityValue != null && quantityValue > 0)
|
||
? quantityValue
|
||
: widget.item.quantity;
|
||
final price = widget.allowEditUnitPrice
|
||
? ((priceValue != null && priceValue >= 0)
|
||
? priceValue
|
||
: widget.item.unitPrice)
|
||
: widget.item.unitPrice;
|
||
final discount = (discountValue != null && discountValue >= 0)
|
||
? discountValue
|
||
: widget.item.discountValue;
|
||
final taxRate = (taxRateValue != null && taxRateValue >= 0)
|
||
? taxRateValue
|
||
: widget.item.taxRate;
|
||
|
||
return widget.item.copyWith(
|
||
quantity: quantity > 0 ? quantity : 1,
|
||
unitPrice: price,
|
||
discountType: _discountType,
|
||
discountValue: discount,
|
||
taxRate: taxRate,
|
||
);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
final updatedItem = _buildUpdatedItem();
|
||
|
||
return Dialog(
|
||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||
child: Container(
|
||
constraints: const BoxConstraints(maxWidth: 500),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
// هدر دیالوگ
|
||
Container(
|
||
padding: const EdgeInsets.all(20),
|
||
decoration: BoxDecoration(
|
||
color: cs.primaryContainer,
|
||
borderRadius: const BorderRadius.only(
|
||
topLeft: Radius.circular(16),
|
||
topRight: Radius.circular(16),
|
||
),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(Icons.edit, color: cs.onPrimaryContainer),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
'ویرایش محصول',
|
||
style: TextStyle(
|
||
fontSize: 18,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onPrimaryContainer,
|
||
),
|
||
),
|
||
if (widget.item.productName != null)
|
||
Text(
|
||
widget.item.productName!,
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
color: cs.onPrimaryContainer.withOpacity(0.8),
|
||
),
|
||
maxLines: 1,
|
||
overflow: TextOverflow.ellipsis,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// محتوای دیالوگ
|
||
Flexible(
|
||
child: SingleChildScrollView(
|
||
padding: const EdgeInsets.all(24),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
// تعداد
|
||
TextField(
|
||
controller: _quantityController,
|
||
decoration: InputDecoration(
|
||
labelText: 'تعداد',
|
||
hintText: 'مثال: 5',
|
||
prefixIcon: const Icon(Icons.numbers),
|
||
border: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
filled: true,
|
||
fillColor: cs.surfaceContainerHighest,
|
||
),
|
||
keyboardType: const TextInputType.numberWithOptions(
|
||
decimal: true,
|
||
),
|
||
inputFormatters: [
|
||
number_utils.EnglishDigitsFormatter(),
|
||
const number_utils.ThousandsSeparatorInputFormatter(
|
||
allowDecimal: true,
|
||
),
|
||
],
|
||
onChanged: (_) => setState(() {}),
|
||
),
|
||
const SizedBox(height: 16),
|
||
// قیمت واحد
|
||
TextField(
|
||
controller: _priceController,
|
||
readOnly: !widget.allowEditUnitPrice,
|
||
showCursor: widget.allowEditUnitPrice,
|
||
enableInteractiveSelection: widget.allowEditUnitPrice,
|
||
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
|
||
color: widget.allowEditUnitPrice
|
||
? null
|
||
: Theme.of(context).colorScheme.onSurfaceVariant,
|
||
),
|
||
decoration: InputDecoration(
|
||
labelText: 'قیمت واحد',
|
||
hintText: widget.allowEditUnitPrice
|
||
? 'مثال: 100,000'
|
||
: AppLocalizations.of(
|
||
context,
|
||
).unitPriceReadOnlyFieldHint,
|
||
helperText: widget.allowEditUnitPrice
|
||
? null
|
||
: AppLocalizations.of(
|
||
context,
|
||
).unitPriceReadOnlyFieldHint,
|
||
helperMaxLines: 2,
|
||
prefixIcon: const Icon(Icons.attach_money),
|
||
suffixText: 'ریال',
|
||
border: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
filled: true,
|
||
fillColor: widget.allowEditUnitPrice
|
||
? cs.surfaceContainerHighest
|
||
: cs.surfaceContainerHigh.withValues(alpha: 0.85),
|
||
),
|
||
keyboardType: const TextInputType.numberWithOptions(
|
||
decimal: true,
|
||
),
|
||
inputFormatters: [
|
||
number_utils.EnglishDigitsFormatter(),
|
||
const number_utils.ThousandsSeparatorInputFormatter(
|
||
allowDecimal: false,
|
||
),
|
||
],
|
||
onChanged: widget.allowEditUnitPrice
|
||
? (_) => setState(() {})
|
||
: null,
|
||
),
|
||
const SizedBox(height: 16),
|
||
// نوع تخفیف و مبلغ تخفیف (در موبایل هر کدام یک سطر تا آیکون % با برچسب قاطی نشود)
|
||
Builder(
|
||
builder: (context) {
|
||
final stackedDiscount =
|
||
MediaQuery.sizeOf(context).width <
|
||
ResponsiveHelper.shellPersistentNavMinWidth;
|
||
final discountDropdown =
|
||
DropdownButtonFormField<String>(
|
||
value: _discountType,
|
||
decoration: InputDecoration(
|
||
labelText: 'نوع تخفیف',
|
||
prefixIcon: const Icon(Icons.percent),
|
||
border: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
filled: true,
|
||
fillColor: cs.surfaceContainerHighest,
|
||
),
|
||
items: const [
|
||
DropdownMenuItem(
|
||
value: 'amount',
|
||
child: Text('مبلغی'),
|
||
),
|
||
DropdownMenuItem(
|
||
value: 'percent',
|
||
child: Text('درصدی'),
|
||
),
|
||
],
|
||
onChanged: (value) {
|
||
if (value != null) {
|
||
setState(() {
|
||
_discountType = value;
|
||
});
|
||
}
|
||
},
|
||
);
|
||
final discountValueField = TextField(
|
||
controller: _discountController,
|
||
decoration: InputDecoration(
|
||
labelText: _discountType == 'percent'
|
||
? 'درصد تخفیف'
|
||
: 'مبلغ تخفیف',
|
||
hintText: _discountType == 'percent'
|
||
? 'مثال: 10'
|
||
: 'مثال: 5,000',
|
||
prefixIcon: Icon(
|
||
_discountType == 'percent'
|
||
? Icons.percent
|
||
: Icons.discount,
|
||
),
|
||
suffixText: _discountType == 'percent'
|
||
? '%'
|
||
: 'ریال',
|
||
border: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
filled: true,
|
||
fillColor: cs.surfaceContainerHighest,
|
||
),
|
||
keyboardType: const TextInputType.numberWithOptions(
|
||
decimal: true,
|
||
),
|
||
inputFormatters: [
|
||
number_utils.EnglishDigitsFormatter(),
|
||
number_utils.ThousandsSeparatorInputFormatter(
|
||
allowDecimal: _discountType == 'percent'
|
||
? false
|
||
: true,
|
||
),
|
||
],
|
||
onChanged: (_) => setState(() {}),
|
||
);
|
||
if (stackedDiscount) {
|
||
return Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
discountDropdown,
|
||
const SizedBox(height: 16),
|
||
discountValueField,
|
||
],
|
||
);
|
||
}
|
||
return Row(
|
||
children: [
|
||
Expanded(flex: 2, child: discountDropdown),
|
||
const SizedBox(width: 12),
|
||
Expanded(flex: 3, child: discountValueField),
|
||
],
|
||
);
|
||
},
|
||
),
|
||
const SizedBox(height: 16),
|
||
// نرخ مالیات
|
||
TextField(
|
||
controller: _taxRateController,
|
||
decoration: InputDecoration(
|
||
labelText: 'نرخ مالیات',
|
||
hintText: 'مثال: 9',
|
||
prefixIcon: const Icon(Icons.receipt_long),
|
||
suffixText: '%',
|
||
border: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(8),
|
||
),
|
||
filled: true,
|
||
fillColor: cs.surfaceContainerHighest,
|
||
),
|
||
keyboardType: const TextInputType.numberWithOptions(
|
||
decimal: true,
|
||
),
|
||
inputFormatters: [
|
||
number_utils.EnglishDigitsFormatter(),
|
||
const number_utils.ThousandsSeparatorInputFormatter(
|
||
allowDecimal: false,
|
||
),
|
||
],
|
||
onChanged: (_) => setState(() {}),
|
||
),
|
||
const SizedBox(height: 24),
|
||
// خلاصه محاسبات
|
||
Container(
|
||
padding: const EdgeInsets.all(16),
|
||
decoration: BoxDecoration(
|
||
color: cs.primaryContainer.withOpacity(0.3),
|
||
borderRadius: BorderRadius.circular(12),
|
||
border: Border.all(
|
||
color: cs.outline.withOpacity(0.2),
|
||
width: 1,
|
||
),
|
||
),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
Icon(
|
||
Icons.calculate,
|
||
size: 20,
|
||
color: cs.primary,
|
||
),
|
||
const SizedBox(width: 8),
|
||
Text(
|
||
'خلاصه محاسبات',
|
||
style: TextStyle(
|
||
fontSize: 16,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onSurface,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 16),
|
||
_buildSummaryRow(
|
||
'جمع کل',
|
||
formatWithThousands(
|
||
updatedItem.subtotal,
|
||
decimalPlaces: widget.currencyDecimalPlaces,
|
||
),
|
||
icon: Icons.summarize,
|
||
),
|
||
if (updatedItem.discountValue > 0) ...[
|
||
const SizedBox(height: 8),
|
||
_buildSummaryRow(
|
||
'تخفیف',
|
||
'-${formatWithThousands(updatedItem.discountAmount, decimalPlaces: widget.currencyDecimalPlaces)}',
|
||
icon: Icons.discount,
|
||
isDiscount: true,
|
||
),
|
||
],
|
||
if (updatedItem.taxRate > 0) ...[
|
||
const SizedBox(height: 8),
|
||
_buildSummaryRow(
|
||
'مالیات',
|
||
formatWithThousands(
|
||
updatedItem.taxAmount,
|
||
decimalPlaces: widget.currencyDecimalPlaces,
|
||
),
|
||
icon: Icons.receipt,
|
||
),
|
||
],
|
||
const Divider(height: 24),
|
||
_buildSummaryRow(
|
||
'مبلغ نهایی',
|
||
formatWithThousands(
|
||
updatedItem.total,
|
||
decimalPlaces: widget.currencyDecimalPlaces,
|
||
),
|
||
icon: Icons.payments,
|
||
isTotal: true,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
// دکمههای پایین
|
||
Container(
|
||
padding: const EdgeInsets.all(16),
|
||
decoration: BoxDecoration(
|
||
color: cs.surfaceContainerHighest,
|
||
borderRadius: const BorderRadius.only(
|
||
bottomLeft: Radius.circular(16),
|
||
bottomRight: Radius.circular(16),
|
||
),
|
||
),
|
||
child: Row(
|
||
mainAxisAlignment: MainAxisAlignment.end,
|
||
children: [
|
||
TextButton.icon(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
icon: const Icon(Icons.cancel_outlined),
|
||
label: const Text('انصراف'),
|
||
style: TextButton.styleFrom(
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 20,
|
||
vertical: 12,
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(width: 8),
|
||
ElevatedButton.icon(
|
||
onPressed: () {
|
||
Navigator.of(context).pop(_buildUpdatedItem());
|
||
},
|
||
icon: const Icon(Icons.check),
|
||
label: const Text('ذخیره تغییرات'),
|
||
style: ElevatedButton.styleFrom(
|
||
backgroundColor: cs.primary,
|
||
foregroundColor: cs.onPrimary,
|
||
padding: const EdgeInsets.symmetric(
|
||
horizontal: 20,
|
||
vertical: 12,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildSummaryRow(
|
||
String label,
|
||
String value, {
|
||
IconData? icon,
|
||
bool isTotal = false,
|
||
bool isDiscount = false,
|
||
}) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
return Row(
|
||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||
crossAxisAlignment: CrossAxisAlignment.center,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
if (icon != null) ...[
|
||
Icon(
|
||
icon,
|
||
size: 18,
|
||
color: isTotal
|
||
? cs.primary
|
||
: (isDiscount ? cs.error : cs.onSurface.withOpacity(0.7)),
|
||
),
|
||
const SizedBox(width: 8),
|
||
],
|
||
Text(
|
||
label,
|
||
style: TextStyle(
|
||
fontSize: isTotal ? 15 : 13,
|
||
fontWeight: isTotal ? FontWeight.bold : FontWeight.w500,
|
||
color: isTotal
|
||
? cs.primary
|
||
: (isDiscount ? cs.error : cs.onSurface),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
Text(
|
||
value,
|
||
style: TextStyle(
|
||
fontWeight: FontWeight.bold,
|
||
color: isTotal
|
||
? cs.primary
|
||
: (isDiscount ? cs.error : cs.onSurface),
|
||
fontSize: isTotal ? 18 : 14,
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Dialog برای انتخاب instance از بین چند نتیجه
|
||
class _InstanceSelectionDialog extends StatelessWidget {
|
||
final List<dynamic> instances;
|
||
final String searchCode;
|
||
|
||
const _InstanceSelectionDialog({
|
||
required this.instances,
|
||
required this.searchCode,
|
||
});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
|
||
return Dialog(
|
||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||
child: Container(
|
||
constraints: const BoxConstraints(maxWidth: 600, maxHeight: 500),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
// هدر
|
||
Container(
|
||
padding: const EdgeInsets.all(20),
|
||
decoration: BoxDecoration(
|
||
color: cs.primaryContainer,
|
||
borderRadius: const BorderRadius.only(
|
||
topLeft: Radius.circular(16),
|
||
topRight: Radius.circular(16),
|
||
),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(Icons.search, color: cs.onPrimaryContainer),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
'چند نتیجه پیدا شد',
|
||
style: TextStyle(
|
||
fontSize: 18,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onPrimaryContainer,
|
||
),
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
'برای "$searchCode"',
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
color: cs.onPrimaryContainer.withOpacity(0.8),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
IconButton(
|
||
icon: Icon(Icons.close, color: cs.onPrimaryContainer),
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// لیست نتایج
|
||
Flexible(
|
||
child: ListView.builder(
|
||
shrinkWrap: true,
|
||
itemCount: instances.length,
|
||
itemBuilder: (context, index) {
|
||
final instance = Map<String, dynamic>.from(
|
||
instances[index] as Map,
|
||
);
|
||
final serialNumber =
|
||
instance['serial_number']?.toString() ?? '-';
|
||
final barcode = instance['barcode']?.toString() ?? '-';
|
||
final productName =
|
||
instance['product_name']?.toString() ?? 'نامشخص';
|
||
final warehouseName = instance['warehouse_name']?.toString();
|
||
|
||
return ListTile(
|
||
leading: const Icon(Icons.inventory_2),
|
||
title: Text(productName),
|
||
subtitle: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
if (serialNumber != '-') Text('سریال: $serialNumber'),
|
||
if (barcode != '-') Text('بارکد: $barcode'),
|
||
if (warehouseName != null)
|
||
Text('انبار: $warehouseName'),
|
||
],
|
||
),
|
||
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
|
||
onTap: () {
|
||
Navigator.of(context).pop(instance);
|
||
},
|
||
);
|
||
},
|
||
),
|
||
),
|
||
// دکمه انصراف
|
||
Container(
|
||
padding: const EdgeInsets.all(16),
|
||
child: SizedBox(
|
||
width: double.infinity,
|
||
child: OutlinedButton(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
child: const Text('انصراف'),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// Dialog برای انتخاب محصول از بین چند نتیجه
|
||
class _ProductSelectionDialog extends StatelessWidget {
|
||
final List<Map<String, dynamic>> products;
|
||
final String searchCode;
|
||
|
||
const _ProductSelectionDialog({
|
||
required this.products,
|
||
required this.searchCode,
|
||
});
|
||
|
||
String _formatNumber(num? value) {
|
||
if (value == null) return '-';
|
||
return value
|
||
.toStringAsFixed(0)
|
||
.replaceAllMapped(
|
||
RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
|
||
(Match m) => '${m[1]},',
|
||
);
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final cs = Theme.of(context).colorScheme;
|
||
|
||
return Dialog(
|
||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||
child: Container(
|
||
constraints: const BoxConstraints(maxWidth: 600, maxHeight: 500),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
// هدر
|
||
Container(
|
||
padding: const EdgeInsets.all(20),
|
||
decoration: BoxDecoration(
|
||
color: cs.primaryContainer,
|
||
borderRadius: const BorderRadius.only(
|
||
topLeft: Radius.circular(16),
|
||
topRight: Radius.circular(16),
|
||
),
|
||
),
|
||
child: Row(
|
||
children: [
|
||
Icon(Icons.search, color: cs.onPrimaryContainer),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
'چند نتیجه پیدا شد',
|
||
style: TextStyle(
|
||
fontSize: 18,
|
||
fontWeight: FontWeight.bold,
|
||
color: cs.onPrimaryContainer,
|
||
),
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
'برای "$searchCode"',
|
||
style: TextStyle(
|
||
fontSize: 14,
|
||
color: cs.onPrimaryContainer.withOpacity(0.8),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
IconButton(
|
||
icon: Icon(Icons.close, color: cs.onPrimaryContainer),
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
// لیست نتایج
|
||
Flexible(
|
||
child: ListView.builder(
|
||
shrinkWrap: true,
|
||
itemCount: products.length,
|
||
itemBuilder: (context, index) {
|
||
final product = products[index];
|
||
final productName = product['name']?.toString() ?? 'نامشخص';
|
||
final productCode = _quickSalesDisplayProductBusinessCode(
|
||
product,
|
||
);
|
||
final showBarcodeLine = !ResponsiveHelper.isMobile(context);
|
||
final barcodeLine = showBarcodeLine
|
||
? productPrimaryBarcodeForSearchDisplay(product)
|
||
: null;
|
||
final salesPrice =
|
||
product['base_sales_price'] ?? product['sales_price'];
|
||
|
||
return ListTile(
|
||
leading: const Icon(Icons.shopping_bag),
|
||
title: Text(productName),
|
||
subtitle: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
if (productCode != null && productCode.isNotEmpty)
|
||
Text('کد: $productCode'),
|
||
if (barcodeLine != null && barcodeLine.isNotEmpty)
|
||
Text('بارکد: $barcodeLine'),
|
||
if (salesPrice != null)
|
||
Text(
|
||
'قیمت: ${_formatNumber(_toNum(salesPrice))} ریال',
|
||
style: TextStyle(
|
||
color: cs.primary,
|
||
fontWeight: FontWeight.bold,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
|
||
onTap: () {
|
||
Navigator.of(context).pop(product);
|
||
},
|
||
);
|
||
},
|
||
),
|
||
),
|
||
// دکمه انصراف
|
||
Container(
|
||
padding: const EdgeInsets.all(16),
|
||
child: SizedBox(
|
||
width: double.infinity,
|
||
child: OutlinedButton(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
child: const Text('انصراف'),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
/// تبدیل مقدار به num (پشتیبانی از String و num)
|
||
num _toNum(dynamic value, {num defaultValue = 0.0}) {
|
||
if (value == null) return defaultValue;
|
||
if (value is num) return value;
|
||
if (value is String) {
|
||
return num.tryParse(value) ?? defaultValue;
|
||
}
|
||
return num.tryParse(value.toString()) ?? defaultValue;
|
||
}
|
||
}
|