expense_edit_page.dart 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:tdesign_flutter/tdesign_flutter.dart';
  6. import 'package:dio/dio.dart';
  7. import 'package:go_router/go_router.dart';
  8. import '../../core/network/api_exception.dart';
  9. import '../../core/utils/responsive.dart';
  10. import '../../core/utils/date_utils.dart' as du;
  11. import '../../shared/widgets/form_section.dart';
  12. import '../../shared/widgets/form_field_row.dart';
  13. import '../../shared/widgets/app_skeletons.dart';
  14. import '../../shared/widgets/nav_bar_config.dart';
  15. import 'widgets/expense_detail_dialog.dart';
  16. import '../../shared/widgets/searchable_picker_sheet.dart';
  17. import '../../shared/widgets/loading_dialog.dart';
  18. import '../../shared/widgets/action_bar.dart';
  19. import 'expense_api.dart';
  20. import '../../core/i18n/app_localizations.dart';
  21. import 'expense_model.dart';
  22. import '../../core/theme/app_colors.dart';
  23. import '../../core/theme/app_colors_extension.dart';
  24. import '../../core/navigation/host_app_channel.dart';
  25. import '../../core/utils/amount_utils.dart';
  26. /// 费用报销修改页
  27. ///
  28. /// 完全参考 [ExpenseCreatePage] 创建页,但:
  29. /// - 无草稿功能
  30. /// - 无附件上传区
  31. /// - 无从申请单导入链接
  32. /// - initState 中加载原单数据并回填
  33. /// - 基本信息区顶部加单号、日期只读行
  34. /// - ActionBar 仅含提交按钮
  35. /// - 提交时 HeadData 加 BX_NO,成功 pop(true) 返回详情页
  36. class ExpenseEditPage extends ConsumerStatefulWidget {
  37. final String billNo;
  38. const ExpenseEditPage({super.key, required this.billNo});
  39. @override
  40. ConsumerState<ExpenseEditPage> createState() => _ExpenseEditPageState();
  41. }
  42. class _ExpenseEditPageState extends ConsumerState<ExpenseEditPage> {
  43. final _purposeController = TextEditingController();
  44. final _purposeFocus = FocusNode();
  45. final _remarkController = TextEditingController();
  46. final _remarkFocus = FocusNode();
  47. final _scrollCtrl = ScrollController();
  48. final _detailsSectionKey = GlobalKey();
  49. // ── 参考数据(从 API 加载) ──
  50. List<CurrencyItem> _currencies = [];
  51. EmployeeItem? _selEmployee;
  52. EmployeeItem? _currentUserForDialog;
  53. dynamic _acctTree;
  54. bool _firstBuild = true;
  55. bool _refDataLoading = true;
  56. bool _addingDetail = false;
  57. bool _isSubmitting = false;
  58. bool _canEditApprovedAmount = false;
  59. String? _loadingError;
  60. // ── 原单数据 ──
  61. ExpenseModel? _expense;
  62. String _billNo = '';
  63. String _expenseDate = '';
  64. // ── 报销部门 ──
  65. String _selectedDeptId = '';
  66. String _selectedDeptName = '';
  67. @override
  68. void initState() {
  69. super.initState();
  70. SystemChrome.setSystemUIOverlayStyle(
  71. const SystemUiOverlayStyle(
  72. statusBarColor: Colors.transparent,
  73. statusBarIconBrightness: Brightness.dark,
  74. ),
  75. );
  76. _purposeFocus.addListener(() => _ensureVisible(_purposeFocus));
  77. _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
  78. _billNo = widget.billNo;
  79. _loadData();
  80. _checkApprovedAmountRight();
  81. }
  82. Future<void> _checkApprovedAmountRight() async {
  83. try {
  84. final api = ref.read(expenseApiProvider);
  85. final ok = await api.checkSpcRight('MONCJ_AMTN_SH');
  86. if (mounted) setState(() => _canEditApprovedAmount = ok);
  87. } catch (_) {
  88. if (mounted) setState(() => _canEditApprovedAmount = false);
  89. }
  90. }
  91. Future<void> _loadData() async {
  92. try {
  93. final api = ref.read(expenseApiProvider);
  94. final results = await Future.wait([
  95. api.getCurrencies(),
  96. api.fetchDetail(widget.billNo),
  97. api.getAcctSubjects(),
  98. api.getEmployees(salNo: HostAppChannel.usr, size: 1),
  99. ]);
  100. if (!mounted) return;
  101. final expense = results[1] as ExpenseModel;
  102. setState(() {
  103. _currencies = results[0] as List<CurrencyItem>;
  104. _acctTree = _convertAcctTree(results[2]);
  105. final currentUserCheck = results[3] as List<EmployeeItem>;
  106. if (currentUserCheck.isNotEmpty) {
  107. _currentUserForDialog = currentUserCheck.first;
  108. }
  109. _expense = expense;
  110. _expenseDate = expense.expenseDate != null
  111. ? du.DateUtils.formatDate(expense.expenseDate!)
  112. : _today();
  113. _selectedDeptId = expense.deptId;
  114. _selectedDeptName = expense.deptName;
  115. _selEmployee = expense.applicantId.isNotEmpty
  116. ? EmployeeItem(
  117. salNo: expense.applicantId,
  118. name: expense.applicantName,
  119. )
  120. : null;
  121. _purposeController.text = expense.purpose;
  122. _remarkController.text = expense.remark;
  123. _refDataLoading = false;
  124. _firstBuild = false;
  125. _recalculateAmount();
  126. });
  127. } catch (e) {
  128. if (!mounted) return;
  129. setState(() {
  130. _refDataLoading = false;
  131. _firstBuild = false;
  132. _loadingError = e.toString();
  133. });
  134. }
  135. }
  136. Future<void> _showEmployeePicker() async {
  137. FocusManager.instance.primaryFocus?.unfocus();
  138. final l10n = AppLocalizations.of(context);
  139. final api = ref.read(expenseApiProvider);
  140. final result = await showSearchablePicker<EmployeeItem>(
  141. context,
  142. title: '${l10n.get('select')}${l10n.get('expensePersonnel')}',
  143. searchHint: l10n.get('search'),
  144. loader: (keyword, page) =>
  145. api.getEmployees(keyword: keyword, page: page, size: 20),
  146. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  147. onRefresh: () => api.clearRefCache(),
  148. );
  149. if (result != null && mounted) {
  150. setState(() => _selEmployee = result);
  151. }
  152. }
  153. void _ensureVisible(FocusNode node) {
  154. if (!node.hasFocus) return;
  155. WidgetsBinding.instance.addPostFrameCallback((_) {
  156. if (node.hasFocus && _scrollCtrl.hasClients) {
  157. final ctx = node.context;
  158. if (ctx != null) {
  159. Scrollable.ensureVisible(
  160. ctx,
  161. alignment: 0.3,
  162. duration: const Duration(milliseconds: 300),
  163. );
  164. }
  165. }
  166. });
  167. }
  168. @override
  169. void dispose() {
  170. _purposeController.dispose();
  171. _purposeFocus.dispose();
  172. _remarkController.dispose();
  173. _remarkFocus.dispose();
  174. _scrollCtrl.dispose();
  175. super.dispose();
  176. }
  177. // ═══ 状态更新助手(替代 Riverpod controller) ═══
  178. void _updatePurpose(String purpose) {
  179. if (_expense == null) return;
  180. setState(() {
  181. _expense = _expense!.copyWith(purpose: purpose);
  182. });
  183. }
  184. void _updateRemark(String remark) {
  185. if (_expense == null) return;
  186. setState(() {
  187. _expense = _expense!.copyWith(remark: remark);
  188. });
  189. }
  190. void _updatePaymentMethod(String method) {
  191. if (_expense == null) return;
  192. setState(() {
  193. _expense = _expense!.copyWith(paymentMethod: method);
  194. });
  195. }
  196. void _updateCurrencyCode(String code, [double excRto = 1.0]) {
  197. if (_expense == null) return;
  198. setState(() {
  199. _expense = _expense!.copyWith(currencyCode: code, excRto: excRto);
  200. });
  201. }
  202. void _setGenerateVoucher(bool value) {
  203. if (_expense == null) return;
  204. setState(() {
  205. _expense = _expense!.copyWith(isGenerateVoucher: value);
  206. });
  207. }
  208. void _addDetail(ExpenseDetailModel detail) {
  209. if (_expense == null) return;
  210. setState(() {
  211. _expense = _expense!.copyWith(details: [..._expense!.details, detail]);
  212. });
  213. _recalculateAmount();
  214. }
  215. void _updateDetail(int index, ExpenseDetailModel detail) {
  216. if (_expense == null) return;
  217. final details = [..._expense!.details];
  218. details[index] = detail;
  219. setState(() {
  220. _expense = _expense!.copyWith(details: details);
  221. });
  222. _recalculateAmount();
  223. }
  224. void _removeDetail(int index) {
  225. if (_expense == null) return;
  226. final details = [..._expense!.details]..removeAt(index);
  227. setState(() {
  228. _expense = _expense!.copyWith(details: details);
  229. });
  230. _recalculateAmount();
  231. }
  232. List<Map<String, dynamic>> _convertAcctTree(dynamic tree) {
  233. if (tree is! List) return [];
  234. return (tree as List).map<Map<String, dynamic>>((item) {
  235. final map = Map<String, dynamic>.from(item is Map ? item : {});
  236. if (map.containsKey('children') && map['children'] != null) {
  237. map['children'] = _convertAcctTree(map['children']);
  238. }
  239. return map;
  240. }).toList();
  241. }
  242. void _recalculateAmount() {
  243. if (_expense == null) return;
  244. var totalAmount = 0.0;
  245. var approvedAmount = 0.0;
  246. for (final d in _expense!.details) {
  247. totalAmount += d.totalAmount;
  248. approvedAmount += d.approvedAmount;
  249. }
  250. setState(() {
  251. _expense = _expense!.copyWith(
  252. totalAmount: totalAmount,
  253. approvedAmount: approvedAmount,
  254. );
  255. });
  256. }
  257. String _currencyLabel(String code) {
  258. final match = _currencies.where((c) => c.curId == code);
  259. return match.isNotEmpty ? '${match.first.curId}/${match.first.name}' : code;
  260. }
  261. Future<void> _showDeptPicker() async {
  262. FocusManager.instance.primaryFocus?.unfocus();
  263. final l10n = AppLocalizations.of(context);
  264. final api = ref.read(expenseApiProvider);
  265. final result = await showSearchablePicker<DepartmentItem>(
  266. context,
  267. title: '${l10n.get('select')}${l10n.get('expenseDept')}',
  268. searchHint: l10n.get('search'),
  269. loader: (keyword, page) =>
  270. api.getDepartments(keyword: keyword, page: page, size: 20),
  271. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  272. onRefresh: () => api.clearRefCache(),
  273. );
  274. if (result != null && mounted) {
  275. setState(() {
  276. _selectedDeptId = result.dep;
  277. _selectedDeptName = result.name;
  278. });
  279. }
  280. }
  281. Map<String, dynamic> _buildSubmitData() {
  282. final expense = _expense!;
  283. return {
  284. 'HeadData': {
  285. 'BX_NO': _billNo,
  286. 'BX_DD': _today(),
  287. 'DEP': _selectedDeptId,
  288. 'USR_NO': _selEmployee?.salNo ?? '',
  289. 'PAY_ID': expense.paymentMethod,
  290. 'USR': HostAppChannel.usr,
  291. 'REM': expense.remark,
  292. 'CUR_ID': expense.currencyCode,
  293. 'EXC_RTO': expense.excRto,
  294. 'REASON': expense.purpose,
  295. 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
  296. },
  297. 'BodyData1': expense.details.asMap().entries.map((e) {
  298. final d = e.value;
  299. final item = <String, dynamic>{
  300. 'BX_NO': _billNo,
  301. 'BX_DD': _today(),
  302. 'ACC_NO': d.acctSubjectId,
  303. 'AMT': d.totalAmount,
  304. 'AMTN': d.amount,
  305. 'AMTN_SH': d.approvedAmount,
  306. 'REM': d.remark,
  307. 'CUST': d.customerVendorId,
  308. 'IDX_NO': d.expenseCategory,
  309. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  310. 'TAX': d.taxAmount,
  311. 'TAX_RTO': d.taxRate,
  312. 'DEP': d.costDeptId,
  313. 'AE_NO': d.aeNo,
  314. 'AE_DD': d.aeDd,
  315. 'BNK_NO': d.bankName,
  316. 'BNK_ID': d.bankAccount,
  317. 'ACCNAME': d.bankAccountName,
  318. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  319. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  320. };
  321. if (d.preItm != null) {
  322. item['PRE_ITM'] = d.preItm;
  323. }
  324. return item;
  325. }).toList(),
  326. };
  327. }
  328. // ═══ Build ═══
  329. @override
  330. Widget build(BuildContext context) {
  331. final r = ResponsiveHelper.of(context);
  332. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  333. final l10n = AppLocalizations.of(context);
  334. final bottomInset = MediaQuery.of(context).padding.bottom;
  335. if (_loadingError != null) {
  336. return Center(
  337. child: Column(
  338. mainAxisSize: MainAxisSize.min,
  339. children: [
  340. Icon(Icons.error_outline, size: 48, color: colors.danger),
  341. const SizedBox(height: 16),
  342. Padding(
  343. padding: const EdgeInsets.symmetric(horizontal: 32),
  344. child: Text(
  345. _loadingError!,
  346. textAlign: TextAlign.center,
  347. style: TextStyle(
  348. fontSize: AppFontSizes.body,
  349. color: colors.textSecondary,
  350. ),
  351. ),
  352. ),
  353. const SizedBox(height: 16),
  354. TDButton(
  355. text: l10n.get('retry'),
  356. size: TDButtonSize.medium,
  357. onTap: () {
  358. setState(() {
  359. _loadingError = null;
  360. _firstBuild = true;
  361. _refDataLoading = true;
  362. });
  363. _loadData();
  364. },
  365. ),
  366. ],
  367. ),
  368. );
  369. }
  370. if (_firstBuild || _expense == null) {
  371. return const SkeletonFormPage(showImportLink: false);
  372. }
  373. Future.microtask(
  374. () => ref.read(pageBackProvider.notifier).state = () => _doPop(l10n),
  375. );
  376. Widget pageContent = PopScope(
  377. canPop: false,
  378. onPopInvokedWithResult: (didPop, _) {
  379. if (didPop) return;
  380. _doPop(l10n);
  381. },
  382. child: Column(
  383. children: [
  384. Expanded(
  385. child: Align(
  386. alignment: Alignment.topCenter,
  387. child: ConstrainedBox(
  388. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  389. child: SingleChildScrollView(
  390. controller: _scrollCtrl,
  391. padding: const EdgeInsets.all(16),
  392. child: Column(
  393. crossAxisAlignment: CrossAxisAlignment.start,
  394. children: [
  395. _buildBasicInfoSection(l10n, colors),
  396. const SizedBox(height: 16),
  397. Container(
  398. key: _detailsSectionKey,
  399. child: _buildDetailSection(l10n, colors),
  400. ),
  401. const SizedBox(height: 24),
  402. _buildPageFooter(),
  403. ],
  404. ),
  405. ),
  406. ),
  407. ),
  408. ),
  409. ColoredBox(
  410. color: colors.bgCard,
  411. child: Column(
  412. mainAxisSize: MainAxisSize.min,
  413. children: [
  414. _buildBottomButtons(l10n),
  415. if (bottomInset > 0) SizedBox(height: bottomInset),
  416. ],
  417. ),
  418. ),
  419. ],
  420. ),
  421. );
  422. return pageContent;
  423. }
  424. Widget _buildBasicInfoSection(
  425. AppLocalizations l10n,
  426. AppColorsExtension colors,
  427. ) {
  428. final expense = _expense!;
  429. return FormSection(
  430. title: l10n.get('basicInfo'),
  431. leadingIcon: Icons.info_outline,
  432. children: [
  433. FormFieldRow(
  434. label: l10n.get('expenseNo'),
  435. value: _billNo,
  436. readOnly: true,
  437. showArrow: false,
  438. ),
  439. const SizedBox(height: 16),
  440. FormFieldRow(
  441. label: l10n.get('date'),
  442. value: _expenseDate,
  443. readOnly: true,
  444. showArrow: false,
  445. ),
  446. const SizedBox(height: 16),
  447. FormFieldRow(
  448. label: l10n.get('expensePersonnel'),
  449. value: _selEmployee != null
  450. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  451. : '',
  452. hint: l10n.get('pleaseSelect'),
  453. onTap: _showEmployeePicker,
  454. ),
  455. const SizedBox(height: 16),
  456. FormFieldRow(
  457. label: l10n.get('expenseDept'),
  458. value: _selectedDeptName.isNotEmpty
  459. ? '$_selectedDeptId/$_selectedDeptName'
  460. : null,
  461. hint: l10n.get('pleaseSelect'),
  462. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  463. ),
  464. const SizedBox(height: 16),
  465. _label(l10n.get('expenseReason'), required: true),
  466. const SizedBox(height: 8),
  467. TDTextarea(
  468. controller: _purposeController,
  469. focusNode: _purposeFocus,
  470. hintText: l10n.get('enterExpenseReason'),
  471. maxLines: 4,
  472. minLines: 1,
  473. maxLength: 500,
  474. indicator: true,
  475. padding: EdgeInsets.zero,
  476. bordered: true,
  477. backgroundColor: colors.bgPage,
  478. onChanged: (_) => _updatePurpose(_purposeController.text),
  479. ),
  480. const SizedBox(height: 16),
  481. FormFieldRow(
  482. label: l10n.get('paymentMethod'),
  483. value: expense.paymentMethod,
  484. hint: l10n.get('pleaseEnter'),
  485. onTap: () => _showTextInput(
  486. l10n.get('paymentMethod'),
  487. (v) => _updatePaymentMethod(v),
  488. initialText: expense.paymentMethod,
  489. ),
  490. onClear: () => _updatePaymentMethod(''),
  491. ),
  492. const SizedBox(height: 16),
  493. FormFieldRow(
  494. label: l10n.get('currency'),
  495. value: expense.currencyCode.isNotEmpty
  496. ? _currencyLabel(expense.currencyCode)
  497. : null,
  498. hint: l10n.get('selectCurrency'),
  499. onTap: () => _showCurrencyPicker(expense.currencyCode),
  500. onClear: () => _updateCurrencyCode(''),
  501. ),
  502. const SizedBox(height: 16),
  503. Row(
  504. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  505. children: [
  506. Text(
  507. l10n.get('generateVoucher'),
  508. style: TextStyle(
  509. fontSize: AppFontSizes.subtitle,
  510. color: colors.textSecondary,
  511. ),
  512. ),
  513. TDSwitch(
  514. isOn: expense.isGenerateVoucher,
  515. onChanged: (v) {
  516. _setGenerateVoucher(v);
  517. return v;
  518. },
  519. ),
  520. ],
  521. ),
  522. const SizedBox(height: 16),
  523. _label(l10n.get('remark')),
  524. const SizedBox(height: 8),
  525. TDTextarea(
  526. controller: _remarkController,
  527. focusNode: _remarkFocus,
  528. hintText: l10n.get('enterRemark'),
  529. maxLines: 3,
  530. minLines: 1,
  531. maxLength: 500,
  532. indicator: true,
  533. padding: EdgeInsets.zero,
  534. bordered: true,
  535. backgroundColor: colors.bgPage,
  536. onChanged: (_) => _updateRemark(_remarkController.text),
  537. ),
  538. ],
  539. );
  540. }
  541. Widget _buildDetailSection(AppLocalizations l10n, AppColorsExtension colors) {
  542. final expense = _expense!;
  543. final totalAmount = expense.details.fold<double>(
  544. 0,
  545. (sum, d) => sum + d.totalAmount,
  546. );
  547. final totalApproved = expense.details.fold<double>(
  548. 0,
  549. (sum, d) => sum + d.approvedAmount,
  550. );
  551. return FormSection(
  552. title: l10n.get('expenseDetails'),
  553. leadingIcon: Icons.receipt_long_outlined,
  554. showAction: true,
  555. actionText: l10n.get('add'),
  556. onActionTap: () => _showAddDetailDialog(),
  557. children: [
  558. if (expense.details.isEmpty)
  559. Padding(
  560. padding: const EdgeInsets.symmetric(vertical: 8),
  561. child: Text(
  562. l10n.get('noDetailHint'),
  563. style: TextStyle(
  564. fontSize: AppFontSizes.subtitle,
  565. color: colors.textPlaceholder,
  566. ),
  567. ),
  568. )
  569. else
  570. ...expense.details.asMap().entries.map((entry) {
  571. final d = entry.value;
  572. return GestureDetector(
  573. onTap: () => _showAddDetailDialog(editIndex: entry.key),
  574. child: Container(
  575. margin: const EdgeInsets.symmetric(vertical: 6),
  576. padding: const EdgeInsets.all(12),
  577. decoration: BoxDecoration(
  578. color: colors.bgPage,
  579. borderRadius: BorderRadius.circular(8),
  580. ),
  581. child: Row(
  582. children: [
  583. Expanded(
  584. child: Column(
  585. crossAxisAlignment: CrossAxisAlignment.start,
  586. children: [
  587. Row(
  588. children: [
  589. Expanded(
  590. child: Text(
  591. d.categoryName.isNotEmpty
  592. ? '${d.expenseCategory}/${d.categoryName}'
  593. : d.expenseCategory,
  594. style: TextStyle(
  595. fontSize: AppFontSizes.body,
  596. fontWeight: FontWeight.w500,
  597. color: colors.textPrimary,
  598. ),
  599. ),
  600. ),
  601. Column(
  602. crossAxisAlignment: CrossAxisAlignment.end,
  603. children: [
  604. Text(
  605. formatAmount(d.totalAmount),
  606. style: TextStyle(
  607. fontSize: AppFontSizes.body,
  608. fontWeight: FontWeight.w600,
  609. color: colors.amountPrimary,
  610. ),
  611. ),
  612. if (d.approvedAmount > 0)
  613. Text(
  614. formatAmount(d.approvedAmount),
  615. style: TextStyle(
  616. fontSize: AppFontSizes.body,
  617. fontWeight: FontWeight.w600,
  618. color: colors.success,
  619. ),
  620. ),
  621. ],
  622. ),
  623. ],
  624. ),
  625. const SizedBox(height: 2),
  626. Text(
  627. '${l10n.get('amountExcludingTax')}: ${formatAmount(d.amount)}',
  628. style: TextStyle(
  629. fontSize: AppFontSizes.caption,
  630. color: colors.textSecondary,
  631. ),
  632. ),
  633. if (d.taxAmount > 0)
  634. Text(
  635. '${l10n.get('taxAmount')}: ${formatAmount(d.taxAmount)}',
  636. style: TextStyle(
  637. fontSize: AppFontSizes.caption,
  638. color: colors.textSecondary,
  639. ),
  640. ),
  641. if (d.taxRate > 0)
  642. Text(
  643. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  644. style: TextStyle(
  645. fontSize: AppFontSizes.caption,
  646. color: colors.textSecondary,
  647. ),
  648. ),
  649. if (d.acctSubjectId.isNotEmpty)
  650. Text(
  651. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  652. maxLines: 1,
  653. overflow: TextOverflow.ellipsis,
  654. style: TextStyle(
  655. fontSize: AppFontSizes.caption,
  656. color: colors.textSecondary,
  657. ),
  658. ),
  659. if (d.aeNo.isNotEmpty)
  660. Text(
  661. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  662. maxLines: 1,
  663. overflow: TextOverflow.ellipsis,
  664. style: TextStyle(
  665. fontSize: AppFontSizes.caption,
  666. color: colors.textSecondary,
  667. ),
  668. ),
  669. if (d.aeDd.isNotEmpty)
  670. Text(
  671. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  672. style: TextStyle(
  673. fontSize: AppFontSizes.caption,
  674. color: colors.textSecondary,
  675. ),
  676. ),
  677. if (d.projectId.isNotEmpty)
  678. Text(
  679. '${l10n.get('project')}: ${d.projectId}${d.projectName.isNotEmpty ? '/${d.projectName}' : ''}',
  680. maxLines: 1,
  681. overflow: TextOverflow.ellipsis,
  682. style: TextStyle(
  683. fontSize: AppFontSizes.caption,
  684. color: colors.textSecondary,
  685. ),
  686. ),
  687. if (d.costDeptId.isNotEmpty)
  688. Text(
  689. '${l10n.get('costDept')}: ${d.costDeptId}${d.costDeptName.isNotEmpty ? '/${d.costDeptName}' : ''}',
  690. maxLines: 1,
  691. overflow: TextOverflow.ellipsis,
  692. style: TextStyle(
  693. fontSize: AppFontSizes.caption,
  694. color: colors.textSecondary,
  695. ),
  696. ),
  697. if (d.customerVendorId.isNotEmpty)
  698. Text(
  699. '${l10n.get('customerVendor')}: ${d.customerVendorId}${d.customerVendorName.isNotEmpty ? '/${d.customerVendorName}' : ''}',
  700. maxLines: 1,
  701. overflow: TextOverflow.ellipsis,
  702. style: TextStyle(
  703. fontSize: AppFontSizes.caption,
  704. color: colors.textSecondary,
  705. ),
  706. ),
  707. if (d.sqMan.isNotEmpty)
  708. Text(
  709. '${l10n.get('applicant')}: ${d.sqMan}${d.sqManName.isNotEmpty ? '/${d.sqManName}' : ''}',
  710. style: TextStyle(
  711. fontSize: AppFontSizes.caption,
  712. color: colors.textSecondary,
  713. ),
  714. ),
  715. if (d.bankAccountName.isNotEmpty)
  716. Text(
  717. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  718. maxLines: 1,
  719. overflow: TextOverflow.ellipsis,
  720. style: TextStyle(
  721. fontSize: AppFontSizes.caption,
  722. color: colors.textSecondary,
  723. ),
  724. ),
  725. if (d.bankName.isNotEmpty)
  726. Text(
  727. '${l10n.get('bankName')}: ${d.bankName}',
  728. maxLines: 1,
  729. overflow: TextOverflow.ellipsis,
  730. style: TextStyle(
  731. fontSize: AppFontSizes.caption,
  732. color: colors.textSecondary,
  733. ),
  734. ),
  735. if (d.bankAccount.isNotEmpty)
  736. Text(
  737. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  738. maxLines: 1,
  739. overflow: TextOverflow.ellipsis,
  740. style: TextStyle(
  741. fontSize: AppFontSizes.caption,
  742. color: colors.textSecondary,
  743. ),
  744. ),
  745. if (d.remark.isNotEmpty)
  746. Text(
  747. '${l10n.get('remark')}: ${d.remark}',
  748. maxLines: 2,
  749. overflow: TextOverflow.ellipsis,
  750. style: TextStyle(
  751. fontSize: AppFontSizes.caption,
  752. color: colors.textSecondary,
  753. ),
  754. ),
  755. ],
  756. ),
  757. ),
  758. const SizedBox(width: 8),
  759. GestureDetector(
  760. onTap: () => _removeDetail(entry.key),
  761. child: Icon(
  762. Icons.close,
  763. size: 18,
  764. color: colors.textSecondary,
  765. ),
  766. ),
  767. ],
  768. ),
  769. ),
  770. );
  771. }),
  772. const SizedBox(height: 8),
  773. Row(
  774. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  775. children: [
  776. Text(
  777. l10n.get('totalExpense'),
  778. style: TextStyle(
  779. fontSize: AppFontSizes.body,
  780. fontWeight: FontWeight.w600,
  781. color: colors.textPrimary,
  782. ),
  783. ),
  784. Text(
  785. formatAmount(totalAmount),
  786. style: TextStyle(
  787. fontSize: AppFontSizes.subtitle,
  788. fontWeight: FontWeight.w700,
  789. color: colors.amountPrimary,
  790. ),
  791. ),
  792. ],
  793. ),
  794. const SizedBox(height: 4),
  795. Row(
  796. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  797. children: [
  798. Text(
  799. l10n.get('approvedTotal'),
  800. style: TextStyle(
  801. fontSize: AppFontSizes.body,
  802. fontWeight: FontWeight.w600,
  803. color: colors.textPrimary,
  804. ),
  805. ),
  806. Text(
  807. formatAmount(totalApproved),
  808. style: TextStyle(
  809. fontSize: AppFontSizes.subtitle,
  810. fontWeight: FontWeight.w700,
  811. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  812. ),
  813. ),
  814. ],
  815. ),
  816. ],
  817. );
  818. }
  819. Future<void> _showAddDetailDialog({int? editIndex}) async {
  820. if (_addingDetail) return;
  821. _addingDetail = true;
  822. try {
  823. final l10n = AppLocalizations.of(context);
  824. final expense = _expense!;
  825. ExpenseDetailInputData? initialData;
  826. if (editIndex != null) {
  827. final d = expense.details[editIndex];
  828. initialData = ExpenseDetailInputData(
  829. category: d.expenseCategory,
  830. categoryName: d.categoryName,
  831. acctSubjectId: d.acctSubjectId,
  832. acctSubjectName: d.acctSubjectName,
  833. purpose: d.purpose,
  834. amount: d.totalAmount,
  835. taxRate: d.taxRate,
  836. projectId: d.projectId,
  837. projectName: d.projectName,
  838. costDeptId: d.costDeptId,
  839. costDeptName: d.costDeptName,
  840. customerVendorId: d.customerVendorId,
  841. customerVendorName: d.customerVendorName,
  842. approvedAmount: d.approvedAmount,
  843. bankName: d.bankName,
  844. bankAccountName: d.bankAccountName,
  845. bankAccount: d.bankAccount,
  846. remark: d.remark,
  847. attachmentPaths: d.attachments,
  848. sqMan: d.sqMan,
  849. sqManName: d.sqManName,
  850. aeNo: d.aeNo,
  851. aeDd: d.aeDd,
  852. );
  853. }
  854. FocusManager.instance.primaryFocus?.unfocus();
  855. final result = await ExpenseDetailDialog.show(
  856. context,
  857. api: ref.read(expenseApiProvider),
  858. l10n: l10n,
  859. initialData: initialData,
  860. checkAttachHealth: () =>
  861. ref.read(expenseApiProvider).checkAttachHealth(),
  862. showAttachments: false,
  863. canEditApprovedAmount: _canEditApprovedAmount,
  864. acctTree: _acctTree,
  865. defaultSqMan: _currentUserForDialog?.salNo,
  866. defaultSqManName: _currentUserForDialog?.name,
  867. );
  868. if (result != null && mounted) {
  869. final now = DateTime.now();
  870. final detail = ExpenseDetailModel(
  871. id: editIndex != null
  872. ? expense.details[editIndex].id
  873. : now.millisecondsSinceEpoch.toString(),
  874. expenseId: '',
  875. expenseCategory: result.category,
  876. categoryName: result.categoryName,
  877. purpose: result.purpose,
  878. amount: result.taxRate > 0
  879. ? result.amount / (1 + result.taxRate / 100)
  880. : result.amount,
  881. taxRate: result.taxRate,
  882. taxAmount: result.taxRate > 0
  883. ? result.amount - result.amount / (1 + result.taxRate / 100)
  884. : 0,
  885. totalAmount: result.amount,
  886. projectId: result.projectId,
  887. projectName: result.projectName,
  888. costDeptId: result.costDeptId,
  889. costDeptName: result.costDeptName,
  890. acctSubjectId: result.acctSubjectId,
  891. acctSubjectName: result.acctSubjectName,
  892. customerVendorId: result.customerVendorId,
  893. customerVendorName: result.customerVendorName,
  894. approvedAmount: result.approvedAmount,
  895. bankName: result.bankName,
  896. bankAccountName: result.bankAccountName,
  897. bankAccount: result.bankAccount,
  898. sqMan: result.sqMan,
  899. sqManName: result.sqManName,
  900. aeNo: result.aeNo,
  901. aeDd: result.aeDd,
  902. remark: result.remark,
  903. sortOrder: editIndex != null
  904. ? expense.details[editIndex].sortOrder
  905. : 1,
  906. preItm: editIndex != null ? expense.details[editIndex].preItm : null,
  907. attachments: result.attachmentPaths,
  908. createTime: now,
  909. updateTime: now,
  910. );
  911. if (editIndex != null) {
  912. _updateDetail(editIndex, detail);
  913. } else {
  914. _addDetail(detail);
  915. }
  916. }
  917. } finally {
  918. _addingDetail = false;
  919. }
  920. }
  921. void _showCurrencyPicker(String cur) {
  922. if (_currencies.isEmpty) {
  923. TDToast.showText(
  924. AppLocalizations.of(context).get('noData'),
  925. context: context,
  926. );
  927. return;
  928. }
  929. final l10n = AppLocalizations.of(context);
  930. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  931. final codes = _currencies.map((c) => c.curId).toList();
  932. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  933. FocusManager.instance.primaryFocus?.unfocus();
  934. TDPicker.showMultiPicker(
  935. context,
  936. title: l10n.get('selectCurrency'),
  937. backgroundColor: colors.bgCard,
  938. data: [labels],
  939. onConfirm: (s) {
  940. if (s.isNotEmpty && s[0] is int) {
  941. final i = s[0] as int;
  942. if (i >= 0 && i < codes.length) {
  943. Navigator.of(context).pop();
  944. _updateCurrencyCode(codes[i], _currencies[i].excRto);
  945. }
  946. }
  947. },
  948. );
  949. }
  950. void _showTextInput(
  951. String title,
  952. Function(String) onConfirm, {
  953. String initialText = '',
  954. }) {
  955. FocusScope.of(context).unfocus();
  956. FocusManager.instance.primaryFocus?.unfocus();
  957. final l10n = AppLocalizations.of(context);
  958. final c = TextEditingController(text: initialText);
  959. showGeneralDialog(
  960. context: context,
  961. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  962. textEditingController: c,
  963. title: title,
  964. hintText: l10n.get('pleaseEnter'),
  965. leftBtn: TDDialogButtonOptions(
  966. title: l10n.get('cancel'),
  967. action: () => Navigator.pop(ctx),
  968. ),
  969. rightBtn: TDDialogButtonOptions(
  970. title: l10n.get('confirm'),
  971. action: () {
  972. onConfirm(c.text);
  973. Navigator.pop(ctx);
  974. },
  975. ),
  976. ),
  977. );
  978. }
  979. Widget _label(String t, {bool required = false}) {
  980. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  981. return Text.rich(
  982. TextSpan(
  983. children: [
  984. TextSpan(
  985. text: t,
  986. style: TextStyle(
  987. fontSize: AppFontSizes.subtitle,
  988. color: colors.textSecondary,
  989. ),
  990. ),
  991. if (required)
  992. TextSpan(
  993. text: ' *',
  994. style: TextStyle(
  995. fontSize: AppFontSizes.subtitle,
  996. color: colors.danger,
  997. ),
  998. ),
  999. ],
  1000. ),
  1001. );
  1002. }
  1003. Widget _buildBottomButtons(AppLocalizations l10n) {
  1004. return ActionBar(
  1005. showLeft: false,
  1006. showCenter: false,
  1007. rightLabel: l10n.get('submit'),
  1008. onRightTap: () async {
  1009. if (_isSubmitting) return;
  1010. final err = _validate(l10n);
  1011. if (err.isNotEmpty) {
  1012. TDToast.showText(err.first, context: context);
  1013. return;
  1014. }
  1015. FocusScope.of(context).unfocus();
  1016. _isSubmitting = true;
  1017. LoadingDialog.show(context, text: l10n.get('submitting'));
  1018. try {
  1019. final data = _buildSubmitData();
  1020. final api = ref.read(expenseApiProvider);
  1021. await api.submit(data);
  1022. if (mounted) {
  1023. LoadingDialog.hide(context);
  1024. TDToast.showSuccess(l10n.get('submitSuccess'), context: context);
  1025. WidgetsBinding.instance.addPostFrameCallback((_) {
  1026. if (mounted) GoRouter.of(context).pop(true);
  1027. });
  1028. }
  1029. } catch (e) {
  1030. if (mounted) {
  1031. LoadingDialog.hide(context);
  1032. WidgetsBinding.instance.addPostFrameCallback((_) {
  1033. if (mounted) _showSubmitError(e, l10n);
  1034. });
  1035. }
  1036. } finally {
  1037. _isSubmitting = false;
  1038. }
  1039. },
  1040. );
  1041. }
  1042. void _showSubmitError(Object e, AppLocalizations l10n) {
  1043. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  1044. showGeneralDialog(
  1045. context: context,
  1046. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  1047. title: l10n.get('submitFailed'),
  1048. content: message,
  1049. buttonStyle: TDDialogButtonStyle.text,
  1050. ),
  1051. );
  1052. }
  1053. String? _extractErrorMessage(Object e) {
  1054. if (e is DioException) {
  1055. if (e.error is ApiException) return (e.error as ApiException).message;
  1056. if (e.error is NetworkException) {
  1057. return (e.error as NetworkException).message;
  1058. }
  1059. }
  1060. return null;
  1061. }
  1062. List<String> _validate(AppLocalizations l10n) {
  1063. final e = <String>[];
  1064. if (_purposeController.text.trim().isEmpty) {
  1065. e.add(l10n.get('enterExpenseReason'));
  1066. }
  1067. if (_expense!.details.isEmpty) {
  1068. e.add(l10n.get('addAtLeastOneDetail'));
  1069. }
  1070. return e;
  1071. }
  1072. bool _hasUnsaved() =>
  1073. _purposeController.text.isNotEmpty ||
  1074. (_expense?.paymentMethod.isNotEmpty ?? false) ||
  1075. (_expense?.currencyCode.isNotEmpty ?? false) ||
  1076. _remarkController.text.isNotEmpty ||
  1077. (_expense?.details.isNotEmpty ?? false);
  1078. void _doPop(AppLocalizations l10n) {
  1079. if (_hasUnsaved()) {
  1080. _showConfirmDialog(
  1081. l10n.get('confirmExit'),
  1082. l10n.get('unsavedContentWarning'),
  1083. l10n.get('continueEditing'),
  1084. l10n.get('discardAndExit'),
  1085. () {
  1086. if (!mounted) return;
  1087. _forcePop();
  1088. },
  1089. );
  1090. } else {
  1091. _forcePop();
  1092. }
  1093. }
  1094. void _forcePop() {
  1095. FocusManager.instance.primaryFocus?.unfocus();
  1096. final router = GoRouter.of(context);
  1097. if (router.canPop()) {
  1098. router.pop();
  1099. } else {
  1100. SystemNavigator.pop();
  1101. }
  1102. }
  1103. void _showConfirmDialog(
  1104. String title,
  1105. String content,
  1106. String leftText,
  1107. String rightText,
  1108. VoidCallback onConfirm,
  1109. ) {
  1110. FocusScope.of(context).unfocus();
  1111. FocusManager.instance.primaryFocus?.unfocus();
  1112. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1113. showDialog(
  1114. context: context,
  1115. useRootNavigator: true,
  1116. builder: (ctx) => TDAlertDialog(
  1117. title: title,
  1118. content: content,
  1119. buttonStyle: TDDialogButtonStyle.text,
  1120. leftBtn: TDDialogButtonOptions(
  1121. title: leftText,
  1122. titleColor: colors.primary,
  1123. action: () => Navigator.pop(ctx),
  1124. ),
  1125. rightBtn: TDDialogButtonOptions(
  1126. title: rightText,
  1127. titleColor: colors.danger,
  1128. action: () {
  1129. Navigator.pop(ctx);
  1130. onConfirm();
  1131. },
  1132. ),
  1133. ),
  1134. );
  1135. }
  1136. Widget _buildPageFooter() {
  1137. final l10n = AppLocalizations.of(context);
  1138. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1139. return Center(
  1140. child: Padding(
  1141. padding: const EdgeInsets.only(bottom: 16),
  1142. child: Row(
  1143. mainAxisSize: MainAxisSize.min,
  1144. children: [
  1145. Icon(
  1146. Icons.rocket_launch_outlined,
  1147. size: 16,
  1148. color: colors.textPlaceholder,
  1149. ),
  1150. const SizedBox(width: 6),
  1151. Text(
  1152. l10n.get('pageFooter'),
  1153. style: TextStyle(
  1154. fontSize: AppFontSizes.caption,
  1155. color: colors.textPlaceholder,
  1156. ),
  1157. ),
  1158. ],
  1159. ),
  1160. ),
  1161. );
  1162. }
  1163. String _today() {
  1164. final n = DateTime.now();
  1165. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1166. }
  1167. }