forked from hesabix/arc
892 lines
30 KiB
Dart
Executable file
892 lines
30 KiB
Dart
Executable file
import 'dart:async';
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import 'package:intl/intl.dart';
|
|
import 'package:hesabix_ui/l10n/app_localizations.dart';
|
|
import 'package:hesabix_ui/core/api_client.dart';
|
|
import '../../widgets/data_table/data_table_widget.dart';
|
|
import '../../widgets/data_table/data_table_config.dart';
|
|
import '../../widgets/person/person_form_dialog.dart';
|
|
import '../../widgets/person/person_import_dialog.dart';
|
|
import '../../widgets/person/person_list_group_filter_bar.dart';
|
|
import '../../widgets/person/person_groups_manage_dialog.dart';
|
|
import '../../widgets/permission/permission_widgets.dart';
|
|
import '../../models/person_model.dart';
|
|
import '../../models/person_group_model.dart';
|
|
import '../../services/person_group_service.dart';
|
|
import '../../services/list_filter_preferences_service.dart';
|
|
import '../../services/person_service.dart';
|
|
import '../../core/auth_store.dart';
|
|
import '../../utils/currency_display_utils.dart';
|
|
import 'person_details_dialog.dart';
|
|
import '../../utils/error_extractor.dart';
|
|
import '../../utils/snackbar_helper.dart';
|
|
import '../../utils/bulk_delete_feedback.dart';
|
|
import '../../services/marketplace_service.dart';
|
|
import '../../widgets/business_subpage_back_leading.dart';
|
|
import 'package:hesabix_ui/theme/semantic_color_resolver.dart';
|
|
|
|
class PersonsPage extends StatefulWidget {
|
|
final int businessId;
|
|
final AuthStore authStore;
|
|
|
|
const PersonsPage({
|
|
super.key,
|
|
required this.businessId,
|
|
required this.authStore,
|
|
});
|
|
|
|
@override
|
|
State<PersonsPage> createState() => _PersonsPageState();
|
|
|
|
/// Static map to store page states by business ID for external refresh
|
|
static final Map<int, _PersonsPageState> _pageStates = {};
|
|
|
|
/// Get the page state for a specific business ID
|
|
static _PersonsPageState? getPageState(int businessId) {
|
|
return _pageStates[businessId];
|
|
}
|
|
|
|
/// Clear the page state for a specific business ID
|
|
static void clearPageState(int businessId) {
|
|
_pageStates.remove(businessId);
|
|
}
|
|
}
|
|
|
|
class _PersonsPageState extends State<PersonsPage> {
|
|
final _personService = PersonService();
|
|
final _personGroupService = PersonGroupService();
|
|
final GlobalKey _personsTableKey = GlobalKey();
|
|
final MarketplaceService _marketplaceService = MarketplaceService();
|
|
List<Map<String, dynamic>> _businessPlugins = [];
|
|
bool _pluginsLoaded = false;
|
|
|
|
List<PersonGroup> _personGroupsForFilter = const [];
|
|
bool _personGroupsLoading = false;
|
|
int? _quickPersonGroupFilterId;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// Register this page instance for external refresh access
|
|
PersonsPage._pageStates[widget.businessId] = this;
|
|
_loadBusinessPlugins();
|
|
_loadPersonGroupsForFilter();
|
|
}
|
|
|
|
Future<void> _loadPersonGroupsForFilter() async {
|
|
setState(() => _personGroupsLoading = true);
|
|
Map<String, dynamic>? saved;
|
|
try {
|
|
saved = await ListFilterPreferencesService.load(ListFilterPageIds.persons, widget.businessId);
|
|
} catch (_) {}
|
|
int? savedGroupId;
|
|
if (saved != null) {
|
|
final raw = saved['person_group_id'];
|
|
if (raw is int) {
|
|
savedGroupId = raw;
|
|
} else if (raw != null) {
|
|
savedGroupId = int.tryParse('$raw');
|
|
}
|
|
}
|
|
try {
|
|
final list = await _personGroupService.listGroups(
|
|
businessId: widget.businessId,
|
|
skip: 0,
|
|
take: 500,
|
|
activeOnly: false,
|
|
rootOnly: true,
|
|
);
|
|
if (!mounted) return;
|
|
final validSaved = savedGroupId != null && list.any((g) => g.id == savedGroupId);
|
|
setState(() {
|
|
_personGroupsForFilter = list;
|
|
_personGroupsLoading = false;
|
|
if (validSaved) {
|
|
_quickPersonGroupFilterId = savedGroupId;
|
|
}
|
|
});
|
|
if (validSaved) {
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (!mounted) return;
|
|
try {
|
|
(_personsTableKey.currentState as dynamic)?.applyPersonGroupIdFilter(savedGroupId);
|
|
} catch (_) {}
|
|
});
|
|
}
|
|
} catch (_) {
|
|
if (mounted) {
|
|
setState(() => _personGroupsLoading = false);
|
|
}
|
|
}
|
|
}
|
|
|
|
void _onQuickPersonGroupFilterChanged(int? groupId) {
|
|
setState(() => _quickPersonGroupFilterId = groupId);
|
|
try {
|
|
(_personsTableKey.currentState as dynamic)?.applyPersonGroupIdFilter(groupId);
|
|
} catch (_) {}
|
|
if (groupId == null) {
|
|
unawaited(ListFilterPreferencesService.clear(ListFilterPageIds.persons, widget.businessId));
|
|
} else {
|
|
unawaited(ListFilterPreferencesService.save(
|
|
ListFilterPageIds.persons,
|
|
widget.businessId,
|
|
<String, dynamic>{'person_group_id': groupId},
|
|
));
|
|
}
|
|
}
|
|
|
|
void _onPersonsDataTableAllFiltersCleared() {
|
|
unawaited(_clearPersonsQuickGroupAndPrefs());
|
|
}
|
|
|
|
Future<void> _clearPersonsQuickGroupAndPrefs() async {
|
|
await ListFilterPreferencesService.clear(ListFilterPageIds.persons, widget.businessId);
|
|
if (!mounted) return;
|
|
setState(() => _quickPersonGroupFilterId = null);
|
|
try {
|
|
(_personsTableKey.currentState as dynamic)?.applyPersonGroupIdFilter(null);
|
|
} catch (_) {}
|
|
refresh();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
// Clean up the page state when disposed
|
|
PersonsPage._pageStates.remove(widget.businessId);
|
|
super.dispose();
|
|
}
|
|
|
|
/// Public method to refresh the data table
|
|
void refresh() {
|
|
try {
|
|
(_personsTableKey.currentState as dynamic)?.refresh();
|
|
} catch (_) {}
|
|
}
|
|
|
|
Future<void> _loadBusinessPlugins() async {
|
|
if (_pluginsLoaded) return;
|
|
try {
|
|
final plugins = await _marketplaceService.listBusinessPlugins(businessId: widget.businessId);
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_businessPlugins = plugins.map((e) => Map<String, dynamic>.from(e as Map)).toList();
|
|
_pluginsLoaded = true;
|
|
});
|
|
} catch (_) {
|
|
// اگر خطا خورد، پیشفرض: پلاگینها را غیرفعال فرض میکنیم تا درخواستهای حساس ارسال نشود.
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_pluginsLoaded = true;
|
|
});
|
|
}
|
|
}
|
|
|
|
bool _isWarrantyPluginActive() {
|
|
try {
|
|
final warrantyPlugin = _businessPlugins.firstWhere(
|
|
(plugin) => plugin['plugin_code'] == 'product_warranty',
|
|
orElse: () => <String, dynamic>{},
|
|
);
|
|
return warrantyPlugin['is_active'] == true;
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final t = AppLocalizations.of(context);
|
|
|
|
// بررسی دسترسی خواندن
|
|
if (!widget.authStore.canReadSection('people')) {
|
|
return AccessDeniedPage(
|
|
message: 'شما دسترسی لازم برای مشاهده لیست اشخاص را ندارید',
|
|
);
|
|
}
|
|
|
|
return Scaffold(
|
|
body: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
PersonListGroupFilterBar(
|
|
groups: _personGroupsForFilter,
|
|
loading: _personGroupsLoading,
|
|
selectedGroupId: _quickPersonGroupFilterId,
|
|
onGroupChanged: _onQuickPersonGroupFilterChanged,
|
|
),
|
|
const Divider(height: 1),
|
|
Expanded(
|
|
child: DataTableWidget<Person>(
|
|
key: _personsTableKey,
|
|
config: _buildDataTableConfig(t),
|
|
fromJson: Person.fromJson,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
DataTableConfig<Person> _buildDataTableConfig(AppLocalizations t) {
|
|
return DataTableConfig<Person>(
|
|
endpoint: '/api/v1/persons/businesses/${widget.businessId}/persons',
|
|
title: t.personsList,
|
|
excelEndpoint: '/api/v1/persons/businesses/${widget.businessId}/persons/export/excel',
|
|
pdfEndpoint: '/api/v1/persons/businesses/${widget.businessId}/persons/export/pdf',
|
|
showExportButtons: true,
|
|
businessId: widget.businessId,
|
|
reportModuleKey: 'persons',
|
|
reportSubtype: 'list',
|
|
getExportParams: () => {
|
|
'business_id': widget.businessId,
|
|
},
|
|
showBackButton: true,
|
|
onBack: () {
|
|
if (!mounted) return;
|
|
popBusinessOrLauncher(context, widget.businessId);
|
|
},
|
|
showTableIcon: false,
|
|
showRowNumbers: true,
|
|
enableRowSelection: true,
|
|
enableMultiRowSelection: true,
|
|
columns: [
|
|
CustomColumn(
|
|
'code',
|
|
t.personCode,
|
|
width: ColumnWidth.small,
|
|
sortable: true,
|
|
formatter: (person) => (person.code?.toString() ?? '-'),
|
|
builder: (person, index) {
|
|
final codeText = person.code?.toString() ?? '-';
|
|
return InkWell(
|
|
onTap: () {
|
|
if (person.id != null) {
|
|
context.go(
|
|
'/business/${widget.businessId}/reports/kardex?person_ids=${person.id}',
|
|
);
|
|
}
|
|
},
|
|
child: Text(
|
|
codeText,
|
|
textAlign: TextAlign.center,
|
|
style: const TextStyle(decoration: TextDecoration.underline),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
TextColumn(
|
|
'alias_name',
|
|
t.personAliasName,
|
|
width: ColumnWidth.large,
|
|
formatter: (person) => person.aliasName,
|
|
),
|
|
TextColumn(
|
|
'first_name',
|
|
t.personFirstName,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.firstName ?? '-',
|
|
),
|
|
TextColumn(
|
|
'last_name',
|
|
t.personLastName,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.lastName ?? '-',
|
|
),
|
|
TextColumn(
|
|
'person_group_name',
|
|
t.personGroupColumn,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.personGroupName ?? '-',
|
|
),
|
|
TextColumn(
|
|
'person_type',
|
|
t.personType,
|
|
width: ColumnWidth.medium,
|
|
filterType: ColumnFilterType.multiSelect,
|
|
filterOptions: [
|
|
FilterOption(value: 'مشتری', label: t.personTypeCustomer),
|
|
FilterOption(value: 'بازاریاب', label: t.personTypeMarketer),
|
|
FilterOption(value: 'کارمند', label: t.personTypeEmployee),
|
|
FilterOption(value: 'تامینکننده', label: t.personTypeSupplier),
|
|
FilterOption(value: 'همکار', label: t.personTypePartner),
|
|
FilterOption(value: 'فروشنده', label: t.personTypeSeller),
|
|
FilterOption(value: 'سهامدار', label: 'سهامدار'),
|
|
],
|
|
formatter: (person) => person.personTypes.map((e) => e.persianName).join('، '),
|
|
),
|
|
TextColumn(
|
|
'company_name',
|
|
t.personCompanyName,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.companyName ?? '-',
|
|
),
|
|
TextColumn(
|
|
'name_prefix',
|
|
t.personNamePrefix,
|
|
width: ColumnWidth.small,
|
|
formatter: (person) =>
|
|
(person.namePrefix != null && person.namePrefix!.trim().isNotEmpty) ? person.namePrefix! : '-',
|
|
),
|
|
TextColumn(
|
|
'legal_entity_type',
|
|
t.personLegalEntityType,
|
|
width: ColumnWidth.small,
|
|
formatter: (person) =>
|
|
person.legalEntityType == 'legal' ? t.personLegalEntityLegal : t.personLegalEntityNatural,
|
|
),
|
|
TextColumn(
|
|
'mobile',
|
|
t.personMobile,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.mobile ?? '-',
|
|
),
|
|
TextColumn(
|
|
'mobile_2',
|
|
t.personMobile2,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.mobile2 ?? '-',
|
|
),
|
|
TextColumn(
|
|
'mobile_3',
|
|
t.personMobile3,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.mobile3 ?? '-',
|
|
),
|
|
TextColumn(
|
|
'email',
|
|
t.personEmail,
|
|
width: ColumnWidth.large,
|
|
formatter: (person) => person.email ?? '-',
|
|
),
|
|
TextColumn(
|
|
'national_id',
|
|
t.personNationalId,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.nationalId ?? '-',
|
|
),
|
|
NumberColumn(
|
|
'share_count',
|
|
t.shareCount,
|
|
width: ColumnWidth.small,
|
|
textAlign: TextAlign.center,
|
|
decimalPlaces: 0,
|
|
),
|
|
NumberColumn(
|
|
'commission_sale_percent',
|
|
t.commissionSalePercentLabel,
|
|
width: ColumnWidth.medium,
|
|
decimalPlaces: 2,
|
|
suffix: '٪',
|
|
),
|
|
NumberColumn(
|
|
'commission_sales_return_percent',
|
|
t.commissionSalesReturnPercentLabel,
|
|
width: ColumnWidth.medium,
|
|
decimalPlaces: 2,
|
|
suffix: '٪',
|
|
),
|
|
NumberColumn(
|
|
'commission_sales_amount',
|
|
t.commissionSalesAmountLabel,
|
|
width: ColumnWidth.large,
|
|
decimalPlaces: 0,
|
|
),
|
|
NumberColumn(
|
|
'commission_sales_return_amount',
|
|
t.commissionSalesReturnAmountLabel,
|
|
width: ColumnWidth.large,
|
|
decimalPlaces: 0,
|
|
),
|
|
TextColumn(
|
|
'payment_id',
|
|
t.personPaymentId,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.paymentId ?? '-',
|
|
),
|
|
TextColumn(
|
|
'registration_number',
|
|
t.personRegistrationNumber,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.registrationNumber ?? '-',
|
|
),
|
|
TextColumn(
|
|
'economic_id',
|
|
t.personEconomicId,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.economicId ?? '-',
|
|
),
|
|
TextColumn(
|
|
'country',
|
|
t.personCountry,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.country ?? '-',
|
|
),
|
|
TextColumn(
|
|
'province',
|
|
t.personProvince,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.province ?? '-',
|
|
),
|
|
TextColumn(
|
|
'city',
|
|
t.personCity,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.city ?? '-',
|
|
),
|
|
TextColumn(
|
|
'address',
|
|
t.personAddress,
|
|
width: ColumnWidth.extraLarge,
|
|
formatter: (person) => person.address ?? '-',
|
|
),
|
|
TextColumn(
|
|
'postal_code',
|
|
t.personPostalCode,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.postalCode ?? '-',
|
|
),
|
|
TextColumn(
|
|
'phone',
|
|
t.personPhone,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.phone ?? '-',
|
|
),
|
|
TextColumn(
|
|
'fax',
|
|
t.personFax,
|
|
width: ColumnWidth.medium,
|
|
formatter: (person) => person.fax ?? '-',
|
|
),
|
|
TextColumn(
|
|
'website',
|
|
t.personWebsite,
|
|
width: ColumnWidth.large,
|
|
formatter: (person) => person.website ?? '-',
|
|
),
|
|
CustomColumn(
|
|
'balance',
|
|
'تراز',
|
|
width: ColumnWidth.medium,
|
|
sortable: true,
|
|
formatter: (person) {
|
|
final balance = person.balance ?? 0.0;
|
|
final formatter = NumberFormat('#,##0', 'en_US');
|
|
return formatter.format(balance.abs());
|
|
},
|
|
builder: (person, index) {
|
|
final balance = person.balance ?? 0.0;
|
|
final formatter = NumberFormat('#,##0', 'en_US');
|
|
final formattedBalance = formatter.format(balance.abs());
|
|
|
|
Color balanceColor;
|
|
if (balance > 0) {
|
|
balanceColor = SemanticColorResolver.positive(context);
|
|
} else if (balance < 0) {
|
|
balanceColor = SemanticColorResolver.negative(context);
|
|
} else {
|
|
balanceColor = Colors.grey;
|
|
}
|
|
|
|
final fxCodes = person.foreignCurrencyCodes;
|
|
final showFx = widget.authStore.isMultiCurrency && fxCodes.isNotEmpty;
|
|
final baseLabel = widget.authStore.currentBusiness?.defaultCurrency?.symbol
|
|
?? widget.authStore.currentBusiness?.defaultCurrency?.code
|
|
?? 'ریال';
|
|
|
|
return Tooltip(
|
|
message: showFx
|
|
? 'مانده معادل پایه ($baseLabel)\nفعال در ارزها: ${fxCodes.join(' · ')}\nبرای جزئیات هر ارز، جزئیات شخص را باز کنید.'
|
|
: 'مانده به $baseLabel',
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
Text(
|
|
formattedBalance,
|
|
style: TextStyle(
|
|
color: balanceColor,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
Text(
|
|
baseLabel,
|
|
style: TextStyle(
|
|
fontSize: 10,
|
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
if (showFx)
|
|
Padding(
|
|
padding: const EdgeInsets.only(top: 2),
|
|
child: Text(
|
|
'چندارزی: ${fxCodes.join(' · ')}',
|
|
style: TextStyle(
|
|
fontSize: 11,
|
|
color: Theme.of(context).colorScheme.primary,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
maxLines: 1,
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
CustomColumn(
|
|
'status',
|
|
'وضعیت',
|
|
width: ColumnWidth.medium,
|
|
filterType: ColumnFilterType.multiSelect,
|
|
filterOptions: [
|
|
FilterOption(value: 'بستانکار', label: 'بستانکار'),
|
|
FilterOption(value: 'بدهکار', label: 'بدهکار'),
|
|
FilterOption(value: 'بالانس', label: 'تسویه'),
|
|
FilterOption(value: 'بدون تراکنش', label: 'بدون تراکنش'),
|
|
],
|
|
formatter: (person) => personBalanceStatusLabel(person.status).isEmpty
|
|
? '-'
|
|
: personBalanceStatusLabel(person.status),
|
|
builder: (person, index) {
|
|
final status = personBalanceStatusLabel(person.status);
|
|
final raw = status.isEmpty ? '-' : status;
|
|
Color statusColor;
|
|
switch (raw) {
|
|
case 'بستانکار':
|
|
statusColor = SemanticColorResolver.positive(context);
|
|
break;
|
|
case 'بدهکار':
|
|
statusColor = SemanticColorResolver.negative(context);
|
|
break;
|
|
case 'تسویه':
|
|
statusColor = SemanticColorResolver.info(context);
|
|
break;
|
|
case 'بدون تراکنش':
|
|
statusColor = Colors.grey;
|
|
break;
|
|
default:
|
|
statusColor = Colors.black;
|
|
}
|
|
return Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
|
decoration: BoxDecoration(
|
|
color: statusColor.withValues(alpha: 0.1),
|
|
borderRadius: BorderRadius.circular(4),
|
|
border: Border.all(color: statusColor.withValues(alpha: 0.3)),
|
|
),
|
|
child: Text(
|
|
raw,
|
|
style: TextStyle(
|
|
color: statusColor,
|
|
fontWeight: FontWeight.bold,
|
|
fontSize: 12,
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
ActionColumn(
|
|
'actions',
|
|
t.actions,
|
|
actions: [
|
|
DataTableAction(
|
|
icon: Icons.view_kanban,
|
|
label: 'کاردکس',
|
|
onTap: (person) {
|
|
if (person is Person && person.id != null) {
|
|
context.go(
|
|
'/business/${widget.businessId}/reports/kardex?person_ids=${person.id}',
|
|
);
|
|
} else if (person is Map<String, dynamic>) {
|
|
final id = person['id'];
|
|
if (id is int) {
|
|
context.go(
|
|
'/business/${widget.businessId}/reports/kardex?person_ids=$id',
|
|
);
|
|
}
|
|
}
|
|
},
|
|
),
|
|
DataTableAction(
|
|
icon: Icons.edit,
|
|
label: t.edit,
|
|
onTap: (person) => _editPerson(person),
|
|
),
|
|
DataTableAction(
|
|
icon: Icons.delete,
|
|
label: t.delete,
|
|
color: SemanticColorResolver.negative(context),
|
|
onTap: (person) => _deletePerson(person),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
searchFields: [
|
|
'code',
|
|
'alias_name',
|
|
'first_name',
|
|
'last_name',
|
|
'company_name',
|
|
'mobile',
|
|
'email',
|
|
'national_id',
|
|
],
|
|
filterFields: [
|
|
'person_type',
|
|
'person_types',
|
|
'person_group_id',
|
|
'country',
|
|
'province',
|
|
],
|
|
onAllFiltersCleared: _onPersonsDataTableAllFiltersCleared,
|
|
defaultPageSize: 20,
|
|
// انتقال دکمه افزودن به اکشنهای هدر جدول با کنترل دسترسی
|
|
customHeaderActions: [
|
|
PermissionButton(
|
|
section: 'people',
|
|
action: 'add',
|
|
authStore: widget.authStore,
|
|
child: Tooltip(
|
|
message: t.addPerson,
|
|
child: IconButton(
|
|
onPressed: _addPerson,
|
|
icon: const Icon(Icons.add),
|
|
),
|
|
),
|
|
),
|
|
PermissionButton(
|
|
section: 'people',
|
|
action: 'edit',
|
|
authStore: widget.authStore,
|
|
child: Tooltip(
|
|
message: t.personGroupsManage,
|
|
child: IconButton(
|
|
onPressed: () {
|
|
showDialog<void>(
|
|
context: context,
|
|
builder: (ctx) => PersonGroupsManageDialog(businessId: widget.businessId),
|
|
).then((_) {
|
|
if (mounted) _loadPersonGroupsForFilter();
|
|
});
|
|
},
|
|
icon: const Icon(Icons.group_work_outlined),
|
|
),
|
|
),
|
|
),
|
|
if (widget.authStore.canDeleteSection('people'))
|
|
Tooltip(
|
|
message: AppLocalizations.of(context).deletePerson,
|
|
child: IconButton(
|
|
onPressed: () async {
|
|
final t = AppLocalizations.of(context);
|
|
try {
|
|
final state = _personsTableKey.currentState as dynamic;
|
|
final items = (state?.getSelectedItems() as List<dynamic>?) ?? const <dynamic>[];
|
|
if (items.isEmpty) {
|
|
SnackBarHelper.showError(context, message: t.noRowsSelectedError);
|
|
return;
|
|
}
|
|
final ids = <int>[];
|
|
for (final row in items) {
|
|
if (row is Person && row.id != null) {
|
|
ids.add(row.id!);
|
|
} else if (row is Map<String, dynamic>) {
|
|
final id = row['id'];
|
|
if (id is int) ids.add(id);
|
|
}
|
|
}
|
|
if (ids.isEmpty) return;
|
|
|
|
final confirm = await showDialog<bool>(
|
|
context: context,
|
|
builder: (ctx) => AlertDialog(
|
|
title: Text(t.deletePerson),
|
|
content: Text(t.deleteConfirm('${ids.length}')),
|
|
actions: [
|
|
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: Text(t.cancel)),
|
|
FilledButton.tonal(onPressed: () => Navigator.of(ctx).pop(true), child: Text(t.delete)),
|
|
],
|
|
),
|
|
);
|
|
if (confirm != true) return;
|
|
|
|
final client = ApiClient();
|
|
final response = await client.post<Map<String, dynamic>>(
|
|
'/api/v1/persons/businesses/${widget.businessId}/persons/bulk-delete',
|
|
data: { 'ids': ids },
|
|
);
|
|
try { ( _personsTableKey.currentState as dynamic)?.refresh(); } catch (_) {}
|
|
if (!context.mounted) return;
|
|
|
|
final result = BulkDeleteResult.fromResponseBody(response.data);
|
|
await BulkDeleteFeedback.show(
|
|
context,
|
|
t,
|
|
result: result,
|
|
allDeletedMessage: t.personsDeletedSuccessfully,
|
|
);
|
|
} catch (e) {
|
|
if (mounted) {
|
|
final t = AppLocalizations.of(context);
|
|
SnackBarHelper.showError(
|
|
context,
|
|
message: '${t.error}: ${ErrorExtractor.forContext(e, context)}',
|
|
);
|
|
}
|
|
}
|
|
},
|
|
icon: const Icon(Icons.delete_sweep_outlined),
|
|
),
|
|
),
|
|
Builder(builder: (context) {
|
|
final theme = Theme.of(context);
|
|
return Tooltip(
|
|
message: t.importFromExcel,
|
|
child: GestureDetector(
|
|
onTap: () async {
|
|
final ok = await showDialog<bool>(
|
|
context: context,
|
|
builder: (context) => PersonImportDialog(businessId: widget.businessId),
|
|
);
|
|
if (ok == true) {
|
|
final state = _personsTableKey.currentState;
|
|
try {
|
|
// ignore: avoid_dynamic_calls
|
|
(state as dynamic)?.refresh();
|
|
} catch (_) {}
|
|
}
|
|
},
|
|
child: Container(
|
|
padding: const EdgeInsets.all(8),
|
|
decoration: BoxDecoration(
|
|
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
|
|
borderRadius: BorderRadius.circular(8),
|
|
border: Border.all(
|
|
color: theme.colorScheme.outline.withValues(alpha: 0.3),
|
|
),
|
|
),
|
|
child: Icon(
|
|
Icons.upload_file,
|
|
size: 16,
|
|
color: theme.colorScheme.onSurfaceVariant,
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}),
|
|
],
|
|
expandBodyHeightToFitRows: true,
|
|
onRowTap: (item) {
|
|
if (item is Person) {
|
|
_showPersonDetails(item);
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
|
|
void _addPerson() {
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) => PersonFormDialog(
|
|
businessId: widget.businessId,
|
|
onSuccess: () {
|
|
final state = _personsTableKey.currentState;
|
|
try {
|
|
// Call public refresh() via dynamic to avoid private state typing
|
|
// ignore: avoid_dynamic_calls
|
|
(state as dynamic)?.refresh();
|
|
} catch (_) {}
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
void _editPerson(Person person) {
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) => PersonFormDialog(
|
|
businessId: widget.businessId,
|
|
person: person,
|
|
onSuccess: () {
|
|
final state = _personsTableKey.currentState;
|
|
try {
|
|
// ignore: avoid_dynamic_calls
|
|
(state as dynamic)?.refresh();
|
|
} catch (_) {}
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
void _deletePerson(Person person) {
|
|
final t = AppLocalizations.of(context);
|
|
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: Text(t.deletePerson),
|
|
content: Text('آیا از حذف شخص "${person.displayName}" مطمئن هستید؟'),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(),
|
|
child: Text(t.cancel),
|
|
),
|
|
TextButton(
|
|
onPressed: () async {
|
|
Navigator.of(context).pop();
|
|
await _performDelete(person);
|
|
},
|
|
style: TextButton.styleFrom(foregroundColor: SemanticColorResolver.negative(context)),
|
|
child: Text(t.delete),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> _performDelete(Person person) async {
|
|
try {
|
|
await _personService.deletePerson(person.id!);
|
|
if (mounted) {
|
|
SnackBarHelper.showSuccess(
|
|
context,
|
|
message: AppLocalizations.of(context).personDeletedSuccessfully,
|
|
);
|
|
// DataTableWidget will automatically refresh
|
|
}
|
|
} catch (e) {
|
|
if (mounted) {
|
|
SnackBarHelper.showError(
|
|
context,
|
|
message: 'خطا در حذف شخص: ${ErrorExtractor.forContext(e, context)}',
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
void _showPersonDetails(Person person) {
|
|
if (person.id == null) return;
|
|
() async {
|
|
if (!_pluginsLoaded) {
|
|
await _loadBusinessPlugins();
|
|
}
|
|
if (!mounted) return;
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) => PersonDetailsDialog(
|
|
businessId: widget.businessId,
|
|
person: person,
|
|
authStore: widget.authStore,
|
|
isWarrantyPluginActive: _isWarrantyPluginActive(),
|
|
),
|
|
);
|
|
}();
|
|
}
|
|
}
|